identifier.ts 660 B

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