identifier.ts 780 B

1234567891011121314151617181920212223242526272829303132
  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. subscription: "sub",
  15. usage: "usg",
  16. user: "usr",
  17. workspace: "wrk",
  18. } as const
  19. export function create(prefix: keyof typeof prefixes, given?: string): string {
  20. if (given) {
  21. if (given.startsWith(prefixes[prefix])) return given
  22. throw new Error(`ID ${given} does not start with ${prefixes[prefix]}`)
  23. }
  24. return [prefixes[prefix], ulid()].join("_")
  25. }
  26. export function schema(prefix: keyof typeof prefixes) {
  27. return z.string().startsWith(prefixes[prefix])
  28. }
  29. }