mirror of
https://github.com/imdap/ruoyi-plus-vben5.git
synced 2026-04-23 00:38:34 +08:00
feat: 使用 Web Crypto API 生成 UUID
This commit is contained in:
@@ -1,42 +1,27 @@
|
||||
const hexList: string[] = [];
|
||||
for (let i = 0; i <= 15; i++) {
|
||||
hexList[i] = i.toString(16);
|
||||
function getBrowserCrypto(): Crypto {
|
||||
const browserCrypto = globalThis.crypto;
|
||||
|
||||
if (!browserCrypto) {
|
||||
throw new Error('Web Crypto API is not available in the current environment.');
|
||||
}
|
||||
|
||||
return browserCrypto;
|
||||
}
|
||||
|
||||
export function buildUUID(): string {
|
||||
let uuid = '';
|
||||
for (let i = 1; i <= 36; i++) {
|
||||
switch (i) {
|
||||
case 9:
|
||||
case 14:
|
||||
case 19:
|
||||
case 24: {
|
||||
uuid += '-';
|
||||
|
||||
break;
|
||||
}
|
||||
case 15: {
|
||||
uuid += 4;
|
||||
|
||||
break;
|
||||
}
|
||||
case 20: {
|
||||
uuid += hexList[(Math.random() * 4) | 8];
|
||||
|
||||
break;
|
||||
}
|
||||
default: {
|
||||
uuid += hexList[Math.trunc(Math.random() * 16)];
|
||||
}
|
||||
}
|
||||
}
|
||||
return uuid.replaceAll('-', '');
|
||||
return getBrowserCrypto().randomUUID().replaceAll('-', '');
|
||||
}
|
||||
|
||||
let unique = 0;
|
||||
export function buildShortUUID(prefix = ''): string {
|
||||
const time = Date.now();
|
||||
const random = Math.floor(Math.random() * 1_000_000_000);
|
||||
const randomBuffer = new Uint32Array(1);
|
||||
|
||||
getBrowserCrypto().getRandomValues(randomBuffer);
|
||||
|
||||
const randomValue = randomBuffer[0];
|
||||
const random = (randomValue ?? 0) % 1_000_000_000;
|
||||
|
||||
unique++;
|
||||
return `${prefix}_${random}${unique}${String(time)}`;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user