60 lines
1.4 KiB
JavaScript
60 lines
1.4 KiB
JavaScript
const crypt = require("crypto");
|
|
|
|
module.exports = {
|
|
/**
|
|
* Generates a unique ID
|
|
* @returns {string} 12-character base64 ID
|
|
*/
|
|
generateUniqueId: () => crypt.randomBytes(9)
|
|
.toString('base64')
|
|
.replace(/[/+]/g, c => c === '/' ? '_' : '-')
|
|
.slice(0, 12),
|
|
|
|
/**
|
|
*
|
|
* @param {number} len How long to set character length
|
|
* @returns alphanumeric string
|
|
*/
|
|
random: function random(len) {
|
|
len = len || 64;
|
|
return crypt.randomBytes(len).toString("hex");
|
|
},
|
|
|
|
// snowflake: function snowflake() {
|
|
|
|
// const flake = new FlakeId({
|
|
// mid: 64,
|
|
// timeOffset: 1431669781,
|
|
// });
|
|
|
|
// return flake.gen();
|
|
// },
|
|
|
|
shortid: function shortid() {
|
|
let str = Buffer.from(crypt.randomUUID()).toString('base64');
|
|
let n = 12;
|
|
|
|
return (str.length > n) ? str.substr(0, n - 1) : str
|
|
},
|
|
|
|
truncate: function truncate(str, n) {
|
|
return (str.length > n) ? str.substr(0, n - 1) : str;
|
|
},
|
|
|
|
randomNum: function (len1) {
|
|
const len2 = len1 || 17;
|
|
const { customAlphabet } = require('nanoid')
|
|
const nanoid = customAlphabet('1234567890', len2)
|
|
return nanoid();
|
|
},
|
|
|
|
isJson: function (str) {
|
|
try {
|
|
JSON.parse(str);
|
|
} catch (e) {
|
|
return false;
|
|
}
|
|
return true;
|
|
}
|
|
};
|