summaryrefslogtreecommitdiffhomepage
path: root/packages/console/core/src/identifier.ts
blob: 8aa324ba07f96b52c70525e25b0f3023fec7ed33 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import { ulid } from "ulid"
import { z } from "zod"

export namespace Identifier {
  const prefixes = {
    account: "acc",
    auth: "aut",
    benchmark: "ben",
    billing: "bil",
    key: "key",
    lite: "lit",
    model: "mod",
    payment: "pay",
    provider: "prv",
    subscription: "sub",
    usage: "usg",
    user: "usr",
    workspace: "wrk",
  } as const

  export function create(prefix: keyof typeof prefixes, given?: string): string {
    if (given) {
      if (given.startsWith(prefixes[prefix])) return given
      throw new Error(`ID ${given} does not start with ${prefixes[prefix]}`)
    }
    return [prefixes[prefix], ulid()].join("_")
  }

  export function schema(prefix: keyof typeof prefixes) {
    return z.string().startsWith(prefixes[prefix])
  }
}