workspace.ts 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. import { z } from "zod"
  2. import { fn } from "./util/fn"
  3. import { Actor } from "./actor"
  4. import { Database } from "./drizzle"
  5. import { Identifier } from "./identifier"
  6. import { UserTable } from "./schema/user.sql"
  7. import { BillingTable } from "./schema/billing.sql"
  8. import { WorkspaceTable } from "./schema/workspace.sql"
  9. import { Key } from "./key"
  10. import { eq, sql } from "drizzle-orm"
  11. export namespace Workspace {
  12. export const create = fn(
  13. z.object({
  14. name: z.string().min(1),
  15. }),
  16. async ({ name }) => {
  17. const account = Actor.assert("account")
  18. const workspaceID = Identifier.create("workspace")
  19. const userID = Identifier.create("user")
  20. await Database.transaction(async (tx) => {
  21. await tx.insert(WorkspaceTable).values({
  22. id: workspaceID,
  23. name,
  24. })
  25. await tx.insert(UserTable).values({
  26. workspaceID,
  27. id: userID,
  28. accountID: account.properties.accountID,
  29. name: "",
  30. role: "admin",
  31. })
  32. await tx.insert(BillingTable).values({
  33. workspaceID,
  34. id: Identifier.create("billing"),
  35. balance: 0,
  36. })
  37. })
  38. await Actor.provide(
  39. "system",
  40. {
  41. workspaceID,
  42. },
  43. () => Key.create({ userID, name: "Default API Key" }),
  44. )
  45. return workspaceID
  46. },
  47. )
  48. export const update = fn(
  49. z.object({
  50. name: z.string().min(1).max(255),
  51. }),
  52. async ({ name }) => {
  53. const workspaceID = Actor.workspace()
  54. return await Database.use((tx) =>
  55. tx
  56. .update(WorkspaceTable)
  57. .set({
  58. name,
  59. })
  60. .where(eq(WorkspaceTable.id, workspaceID)),
  61. )
  62. },
  63. )
  64. export const remove = fn(z.void(), async () => {
  65. await Database.use((tx) =>
  66. tx
  67. .update(WorkspaceTable)
  68. .set({ timeDeleted: sql`now()` })
  69. .where(eq(WorkspaceTable.id, Actor.workspace())),
  70. )
  71. })
  72. }