use native generators
This commit is contained in:
parent
55118df538
commit
8bb87f9ea4
|
@ -1,14 +1,9 @@
|
||||||
import { init, createId } from "@paralleldrive/cuid2";
|
|
||||||
import config from "@/config/index.js";
|
import config from "@/config/index.js";
|
||||||
|
import { nativeCreateId, nativeInitIdGenerator } from "native-utils/built";
|
||||||
|
|
||||||
const TIME2000 = 946684800000;
|
const length = Math.min(Math.max(config.cuid?.length ?? 16, 16), 24);
|
||||||
const TIMESTAMP_LENGTH = 8;
|
const fingerprint = config.cuid?.fingerprint ?? "";
|
||||||
|
nativeInitIdGenerator(length, fingerprint);
|
||||||
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 });
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The generated ID results in the form of `[8 chars timestamp] + [cuid2]`.
|
* 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
|
* Ref: https://github.com/paralleldrive/cuid2#parameterized-length
|
||||||
*/
|
*/
|
||||||
export function genId(date?: Date): string {
|
export function genId(date?: Date): string {
|
||||||
const now = (date ?? new Date()).getTime();
|
return nativeCreateId(BigInt((date ?? new Date()).getTime()));
|
||||||
const time = Math.max(now - TIME2000, 0);
|
|
||||||
const timestamp = time.toString(36).padStart(TIMESTAMP_LENGTH, "0");
|
|
||||||
|
|
||||||
return `${timestamp}${genCuid2()}`;
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,24 +1,5 @@
|
||||||
import * as crypto from "node:crypto";
|
import { nativeRandomStr } from "native-utils/built";
|
||||||
|
|
||||||
const L_CHARS = "0123456789abcdefghijklmnopqrstuvwxyz";
|
export function secureRndstr(length = 32, _ = true): string {
|
||||||
const LU_CHARS =
|
return nativeRandomStr(length);
|
||||||
"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;
|
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in New Issue