identifier.ts 699 B

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