identifier.ts 801 B

123456789101112131415161718192021222324252627282930313233
  1. import { ulid } from "ulid"
  2. import { z } from "zod"
  3. export namespace Identifier {
  4. const prefixes = {
  5. account: "acc",
  6. auth: "aut",
  7. benchmark: "ben",
  8. billing: "bil",
  9. key: "key",
  10. lite: "lit",
  11. model: "mod",
  12. payment: "pay",
  13. provider: "prv",
  14. referral: "ref",
  15. subscription: "sub",
  16. usage: "usg",
  17. user: "usr",
  18. workspace: "wrk",
  19. } as const
  20. export function create(prefix: keyof typeof prefixes, given?: string): string {
  21. if (given) {
  22. if (given.startsWith(prefixes[prefix])) return given
  23. throw new Error(`ID ${given} does not start with ${prefixes[prefix]}`)
  24. }
  25. return [prefixes[prefix], ulid()].join("_")
  26. }
  27. export function schema(prefix: keyof typeof prefixes) {
  28. return z.string().startsWith(prefixes[prefix])
  29. }
  30. }