identifier.ts 716 B

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