identifier.ts 678 B

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