identifier.ts 763 B

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