summaryrefslogtreecommitdiffhomepage
path: root/packages/console/core/src/account.ts
blob: cb123e0485de81e00d5e18b0c6b1f8d492d1d915 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import { z } from "zod"
import { and, eq, getTableColumns, isNull } from "drizzle-orm"
import { fn } from "./util/fn"
import { Database } from "./drizzle"
import { Identifier } from "./identifier"
import { AccountTable } from "./schema/account.sql"
import { Actor } from "./actor"
import { WorkspaceTable } from "./schema/workspace.sql"
import { UserTable } from "./schema/user.sql"

export namespace Account {
  export const create = fn(
    z.object({
      email: z.string().email(),
      id: z.string().optional(),
    }),
    async (input) =>
      Database.transaction(async (tx) => {
        const id = input.id ?? Identifier.create("account")
        await tx.insert(AccountTable).values({
          id,
          email: input.email,
        })
        return id
      }),
  )

  export const fromID = fn(z.string(), async (id) =>
    Database.transaction(async (tx) => {
      return tx
        .select()
        .from(AccountTable)
        .where(eq(AccountTable.id, id))
        .execute()
        .then((rows) => rows[0])
    }),
  )

  export const fromEmail = fn(z.string().email(), async (email) =>
    Database.transaction(async (tx) => {
      return tx
        .select()
        .from(AccountTable)
        .where(eq(AccountTable.email, email))
        .execute()
        .then((rows) => rows[0])
    }),
  )

  export const workspaces = async () => {
    const actor = Actor.assert("account")
    return Database.transaction(async (tx) =>
      tx
        .select(getTableColumns(WorkspaceTable))
        .from(WorkspaceTable)
        .innerJoin(UserTable, eq(UserTable.workspaceID, WorkspaceTable.id))
        .where(
          and(
            eq(UserTable.email, actor.properties.email),
            isNull(UserTable.timeDeleted),
            isNull(WorkspaceTable.timeDeleted),
          ),
        )
        .execute(),
    )
  }
}