UNPKG

uid-promise

Version:

generates a cryptographically strong random uid

37 lines (36 loc) 1.17 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.generateUidFunction = void 0; // the file extension is needed for ESM const chars_js_1 = require("./chars.js"); const generateUidFunction = (randomBytes) => (len) => new Promise(async (resolve, reject) => { if (!Number.isInteger(len)) { reject(new TypeError('You must supply a length integer to `uid-promise`.')); return; } if (len <= 0) { reject(new Error('You must supply a length integer greater than zero')); return; } randomBytes(len, (err, buf) => { if (err) { return reject(err); } const str = []; let rand; for (let i = 0; i < buf.length; i++) { rand = buf[i]; while (rand > 248) { try { rand = randomBytes(1)[0]; } catch (err) { reject(err); } } str.push(chars_js_1.UIDCHARS[rand % chars_js_1.UIDCHARS.length]); } resolve(str.join('')); }); }); exports.generateUidFunction = generateUidFunction;