Files
SargaTrxUsdPrice/lib/utils.js
2025-05-13 19:41:33 +02:00

74 lines
1.9 KiB
JavaScript

'use strict'
// Libraries
const { customAlphabet } = require('nanoid')
const StringCrypto = require('string-crypto')
const path = require('path')
// NanoId with custom alphabet
const newId = (len) => {
const nanoid = customAlphabet(
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789',
len || 21
)
return nanoid()
}
// Remove all _id
const removeFieldByName = (o, fieldName) => {
delete o[fieldName]
for (let v of Object.values(o))
if (v instanceof Object) removeFieldByName(v, fieldName)
}
// Clean object from unnecesary fields
const fieldsToRemove = ['_id']
const cleanObject = (o) => {
const obj = JSON.parse(JSON.stringify(o))
fieldsToRemove.forEach((f) => {
removeFieldByName(obj, f)
})
return obj
}
// Securize sensible data
const cryptoOptions = {
salt: process.env.CRYPTO_SALT,
iterations: parseInt(process.env.CRYPTO_ITERATIONS),
digest: process.env.CRYPTO_DIGEST // one of: 'blake2b512' | 'blake2s256' | 'md4' | 'md5' | 'md5-sha1' | 'mdc2' | 'ripemd160' | 'sha1' | 'sha224' | 'sha256' | 'sha3-224' | 'sha3-256' | 'sha3-384' | 'sha3-512' | 'sha384' | 'sha512' | 'sha512-224' | 'sha512-256' | 'sm3' | 'whirlpool';
}
const stringCypto = new StringCrypto(cryptoOptions)
const encryptString = (value, password) => {
return stringCypto.encryptString(value, password)
}
const decryptString = (value, password) => {
return stringCypto.decryptString(value, password)
}
// Split array into pieces
const chunk = (arr, size) =>
arr.reduce(
(acc, _, i) => (i % size ? acc : [...acc, arr.slice(i, i + size)]),
[]
)
// Sleep
const sleep = (segundos) => {
return new Promise((resolve) => setTimeout(resolve, segundos * 1000))
}
// Get file name
const getFileName = (f) => path.basename(f, '.js')
module.exports = {
newId,
removeFieldByName,
cleanObject,
encryptString,
decryptString,
chunk,
sleep,
getFileName
}