workspace.ts 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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. Actor.assertAdmin()
  54. const workspaceID = Actor.workspace()
  55. return await Database.use((tx) =>
  56. tx
  57. .update(WorkspaceTable)
  58. .set({
  59. name,
  60. })
  61. .where(eq(WorkspaceTable.id, workspaceID)),
  62. )
  63. },
  64. )
  65. export const remove = fn(z.void(), async () => {
  66. await Database.use((tx) =>
  67. tx
  68. .update(WorkspaceTable)
  69. .set({ timeDeleted: sql`now()` })
  70. .where(eq(WorkspaceTable.id, Actor.workspace())),
  71. )
  72. })
  73. }