workspace.ts 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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. import { Key } from "./key"
  11. export namespace Workspace {
  12. export const create = fn(z.void(), async () => {
  13. const account = Actor.assert("account")
  14. const workspaceID = Identifier.create("workspace")
  15. await Database.transaction(async (tx) => {
  16. await tx.insert(WorkspaceTable).values({
  17. id: workspaceID,
  18. })
  19. await tx.insert(UserTable).values({
  20. workspaceID,
  21. id: Identifier.create("user"),
  22. email: account.properties.email,
  23. name: "",
  24. })
  25. await tx.insert(BillingTable).values({
  26. workspaceID,
  27. id: Identifier.create("billing"),
  28. balance: 0,
  29. })
  30. })
  31. await Actor.provide(
  32. "system",
  33. {
  34. workspaceID,
  35. },
  36. async () => {
  37. await Key.create({ name: "Default API Key" })
  38. },
  39. )
  40. return workspaceID
  41. })
  42. export async function list() {
  43. const account = Actor.assert("account")
  44. return Database.use(async (tx) => {
  45. return tx
  46. .select({
  47. id: WorkspaceTable.id,
  48. slug: WorkspaceTable.slug,
  49. name: WorkspaceTable.name,
  50. })
  51. .from(UserTable)
  52. .innerJoin(WorkspaceTable, eq(UserTable.workspaceID, WorkspaceTable.id))
  53. .where(eq(UserTable.email, account.properties.email))
  54. })
  55. }
  56. }