Skip to content

Commit

Permalink
feat: add support to nanoid
Browse files Browse the repository at this point in the history
  • Loading branch information
JonDotsoy committed Sep 11, 2024
1 parent 8186db2 commit 6c73596
Showing 1 changed file with 10 additions and 0 deletions.
10 changes: 10 additions & 0 deletions uid.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { getProcessor, version } from "./load-version" with { type: "macro" }
import { ulid } from "ulid";
import { ObjectId } from "bson";
import { flag, flags, isNumberAt, Rule, Test, makeHelmMessage, describe } from "@jondotsoy/flags";
import * as nanoid from "nanoid";

const SpecDescribeSymbol = Symbol("SpecDescribeSymbol");
type SpecDescribe = {
Expand All @@ -16,6 +17,7 @@ enum IDKind {
uuid = "uuid",
ulid = "ulid",
objectid = "objectid",
nanoid = "nanoid",
}

enum HandlerKind {
Expand All @@ -28,9 +30,11 @@ let outputIDKind = IDKind.ulid;
let handlerKind = HandlerKind.render_id;
let endWithNewLine = true;
let ulidSeedTime: number | undefined;
let nanoidSize: number | undefined;

type FlagsOptions = {
ulidSeedTime: number;
nanoidSize: number;
};

const flagsRules: Rule<FlagsOptions>[] = [
Expand All @@ -41,6 +45,8 @@ const flagsRules: Rule<FlagsOptions>[] = [
isNumberAt("ulidSeedTime"),
],
[describe(flag("--objectid"), { description: 'make a objectid value' }), () => outputIDKind = IDKind.objectid],
[describe(flag("--nanoid"), { description: 'make a nanoid value' }), () => outputIDKind = IDKind.nanoid],
[describe(flag("--nanoid-size"), { description: 'nanoid size' }), isNumberAt("nanoidSize")],
[describe(flag("--zero", "-z"), { description: 'ignore newline on output' }), () => endWithNewLine = false],
[describe(flag("--version", "-v"), { description: 'display version' }), () => handlerKind = HandlerKind.version],
[describe(flag("--help", "-h"), { description: 'display this help' }), () => handlerKind = HandlerKind.help],
Expand All @@ -56,6 +62,9 @@ const printCommands: Record<IDKind, () => Uint8Array | Promise<Uint8Array>> = {
objectid() {
return new TextEncoder().encode(new ObjectId().toHexString());
},
nanoid() {
return new TextEncoder().encode(nanoid.nanoid(nanoidSize));
},
};

const handlers = {
Expand All @@ -80,6 +89,7 @@ const handlers = {
const parsed = flags<FlagsOptions>(Bun.argv.slice(2), {}, flagsRules);

ulidSeedTime = parsed.ulidSeedTime;
nanoidSize = parsed.nanoidSize;

const output = await handlers[handlerKind]();

Expand Down

0 comments on commit 6c73596

Please sign in to comment.