quantique-converter
Version:
Converters for all kind of data
55 lines (51 loc) • 1.39 kB
JavaScript
const base64 = require('base-64');
const utf8 = require('utf8');
const convertTob64 = (value, parameters = { purpose: 'enc', dataType: '' }) => {
if (parameters?.purpose === 'enc') {
if (parameters?.dataType === 'string') {
const stringifyValue = JSON.stringify(value);
const bytes = utf8.encode(stringifyValue);
const encoded = base64.encode(bytes);
return {
isValid: true,
error: '',
convertedValue: encoded,
};
} else {
const bytes = utf8.encode(value);
const encoded = base64.encode(bytes);
return {
isValid: true,
error: '',
convertedValue: encoded,
};
}
}
if (parameters?.purpose === 'dec') {
try {
const bytes = base64.decode(value);
const decoded = utf8.decode(bytes);
if (parameters?.dataType === 'parsed') {
const parsedDecoded = JSON.parse(decoded);
return {
isValid: true,
error: '',
convertedValue: parsedDecoded,
};
} else {
return {
isValid: true,
error: '',
convertedValue: decoded,
};
}
} catch (e) {
return {
isValid: false,
error: 'Unable to decrypt',
convertedValue: null,
};
}
}
};
module.exports = convertTob64;