account.ts 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. import { z } from "zod"
  2. import { and, eq, inArray, sql } from "drizzle-orm"
  3. import { fn } from "./util/fn"
  4. import { Database } from "./drizzle"
  5. import { Identifier } from "./identifier"
  6. import { AccountTable } from "./schema/account.sql"
  7. import { AuthTable } from "./schema/auth.sql"
  8. import { UserTable } from "./schema/user.sql"
  9. import { KeyTable } from "./schema/key.sql"
  10. import { CouponTable } from "./schema/billing.sql"
  11. export namespace Account {
  12. export const create = fn(
  13. z.object({
  14. id: z.string().optional(),
  15. }),
  16. async (input) =>
  17. Database.use(async (tx) => {
  18. const id = input.id ?? Identifier.create("account")
  19. await tx.insert(AccountTable).values({
  20. id,
  21. })
  22. return id
  23. }),
  24. )
  25. export const remove = fn(z.email(), async (email) => {
  26. await Database.transaction(async (tx) => {
  27. const account = await tx
  28. .select({ id: AccountTable.id })
  29. .from(AuthTable)
  30. .innerJoin(AccountTable, eq(AccountTable.id, AuthTable.accountID))
  31. .where(and(eq(AuthTable.provider, "email"), eq(AuthTable.subject, email)))
  32. .then((rows) => rows[0])
  33. if (!account) throw new Error("Account not found")
  34. const emails = await tx
  35. .select({ email: AuthTable.subject })
  36. .from(AuthTable)
  37. .where(and(eq(AuthTable.accountID, account.id), eq(AuthTable.provider, "email")))
  38. const users = await tx.select({ id: UserTable.id }).from(UserTable).where(eq(UserTable.accountID, account.id))
  39. if (users.length > 0) {
  40. await tx
  41. .update(KeyTable)
  42. .set({ timeDeleted: sql`now()` })
  43. .where(
  44. inArray(
  45. KeyTable.userID,
  46. users.map((user) => user.id),
  47. ),
  48. )
  49. }
  50. await tx
  51. .update(UserTable)
  52. .set({ accountID: null, email: null, name: "", timeDeleted: sql`now()` })
  53. .where(eq(UserTable.accountID, account.id))
  54. if (emails.length > 0) {
  55. await tx.delete(CouponTable).where(
  56. inArray(
  57. CouponTable.email,
  58. emails.map((row) => row.email),
  59. ),
  60. )
  61. }
  62. await tx.delete(AuthTable).where(eq(AuthTable.accountID, account.id))
  63. await tx
  64. .update(AccountTable)
  65. .set({ timeDeleted: sql`now()` })
  66. .where(eq(AccountTable.id, account.id))
  67. })
  68. })
  69. export const fromID = fn(z.string(), async (id) =>
  70. Database.use((tx) =>
  71. tx
  72. .select()
  73. .from(AccountTable)
  74. .where(eq(AccountTable.id, id))
  75. .then((rows) => rows[0]),
  76. ),
  77. )
  78. }