use native generators

This commit is contained in:
Namekuji 2023-06-02 15:01:03 -04:00
parent 55118df538
commit 8bb87f9ea4
No known key found for this signature in database
GPG Key ID: B541BD6E646CABC7
2 changed files with 8 additions and 36 deletions

View File

@ -1,14 +1,9 @@
import { init, createId } from "@paralleldrive/cuid2";
import config from "@/config/index.js";
import { nativeCreateId, nativeInitIdGenerator } from "native-utils/built";
const TIME2000 = 946684800000;
const TIMESTAMP_LENGTH = 8;
const length =
Math.min(Math.max(config.cuid?.length ?? 16, 16), 24) - TIMESTAMP_LENGTH;
const fingerprint = `${config.cuid?.fingerprint ?? ""}${createId()}`;
const genCuid2 = init({ length, fingerprint });
const length = Math.min(Math.max(config.cuid?.length ?? 16, 16), 24);
const fingerprint = config.cuid?.fingerprint ?? "";
nativeInitIdGenerator(length, fingerprint);
/**
* The generated ID results in the form of `[8 chars timestamp] + [cuid2]`.
@ -19,9 +14,5 @@ const genCuid2 = init({ length, fingerprint });
* Ref: https://github.com/paralleldrive/cuid2#parameterized-length
*/
export function genId(date?: Date): string {
const now = (date ?? new Date()).getTime();
const time = Math.max(now - TIME2000, 0);
const timestamp = time.toString(36).padStart(TIMESTAMP_LENGTH, "0");
return `${timestamp}${genCuid2()}`;
return nativeCreateId(BigInt((date ?? new Date()).getTime()));
}

View File

@ -1,24 +1,5 @@
import * as crypto from "node:crypto";
import { nativeRandomStr } from "native-utils/built";
const L_CHARS = "0123456789abcdefghijklmnopqrstuvwxyz";
const LU_CHARS =
"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
export function secureRndstr(length = 32, useLU = true): string {
const chars = useLU ? LU_CHARS : L_CHARS;
const chars_len = chars.length;
let str = "";
for (let i = 0; i < length; i++) {
let rand = Math.floor(
(crypto.randomBytes(1).readUInt8(0) / 0xff) * chars_len,
);
if (rand === chars_len) {
rand = chars_len - 1;
}
str += chars.charAt(rand);
}
return str;
export function secureRndstr(length = 32, _ = true): string {
return nativeRandomStr(length);
}