identifier.ts 738 B

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