workspace.ts 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. import { z } from "zod"
  2. import { fn } from "./util/fn"
  3. import { centsToMicroCents } from "./util/price"
  4. import { Actor } from "./actor"
  5. import { Database, eq } from "./drizzle"
  6. import { Identifier } from "./identifier"
  7. import { UserTable } from "./schema/user.sql"
  8. import { BillingTable } from "./schema/billing.sql"
  9. import { WorkspaceTable } from "./schema/workspace.sql"
  10. export namespace Workspace {
  11. export const create = fn(z.void(), async () => {
  12. const account = Actor.assert("account")
  13. const workspaceID = Identifier.create("workspace")
  14. await Database.transaction(async (tx) => {
  15. await tx.insert(WorkspaceTable).values({
  16. id: workspaceID,
  17. })
  18. await tx.insert(UserTable).values({
  19. workspaceID,
  20. id: Identifier.create("user"),
  21. email: account.properties.email,
  22. name: "",
  23. })
  24. await tx.insert(BillingTable).values({
  25. workspaceID,
  26. id: Identifier.create("billing"),
  27. balance: centsToMicroCents(100),
  28. })
  29. })
  30. return workspaceID
  31. })
  32. export async function list() {
  33. const account = Actor.assert("account")
  34. return Database.use(async (tx) => {
  35. return tx
  36. .select({
  37. id: WorkspaceTable.id,
  38. slug: WorkspaceTable.slug,
  39. name: WorkspaceTable.name,
  40. })
  41. .from(UserTable)
  42. .innerJoin(WorkspaceTable, eq(UserTable.workspaceID, WorkspaceTable.id))
  43. .where(eq(UserTable.email, account.properties.email))
  44. })
  45. }
  46. }