'use strict';
/**
* UUID GENERATOR
*/
import { isObject, sortObjectAttributes } from './index.js';
import { v5 } from 'uuid';
/**
* @module cpb-common/uuid
*/
/**
* UUID v5 Namespace
* @const NAMESPACE="e5d6d7b4-a400-4498-be0f-a75d783e5a06"
* @type {string}
*/
const NAMESPACE = 'e5d6d7b4-a400-4498-be0f-a75d783e5a06';
/**
* remove nested object property from the data object
* @param {{}} data - source data
* @param {string[]} [attr=[]] - attributes to remove
* @returns {{}} data cleaned up data object
*/
const removeNestedProperty = (data = {}, attrs = []) => {
let piece,
cmdAtt = 'data',
removedVal;
while ((piece = attrs.shift())) {
const parts = piece.split('.');
for (let part of parts) {
part = part.toLowerCase();
cmdAtt = `${cmdAtt}['${part}']`;
}
try {
eval(`removedVal = ${cmdAtt}; delete ${cmdAtt};`);
} catch (e) {
console.error(`removedVal = ${cmdAtt}; delete ${cmdAtt};`);
throw e;
}
// title( "FINAL", { removedAtt: piece, removedVal }, 1 );
cmdAtt = 'data';
}
return data;
};
/**
* create unique v5 uuid from the supplied data
* @param {*} [data=CURRENT_TIMESTAMP] - data to generate uuid from
* @param {string[]} [excluded=[]] - attributes excluded from the hashing
* @returns {string} uuid - uuid v5 from hashed object data
* @export
*/
export const uuid = (data, excluded = []) => {
let source;
const attrs = [...excluded, 'filename', 'imported_at', 'uuid'];
if (!data) source = new Date().toString();
if (isObject(data)) {
data = sortObjectAttributes(data);
for (const att of attrs) {
delete data[att];
}
source = JSON.stringify(data);
} else source = (data || '').toString();
return v5(source, NAMESPACE);
};
/**
* create v5 uuid from the url in the URL namespace
* @param {string} url
* @returns {string} uuid
* @export
*/
export const uuidFromUrl = url => v5(url, v5.URL);
export default { uuid, uuidFromUrl };