/**
* Hashes metadata values for an experiment with defensive checks.
*
* @param {object} metadata - An object containing the metadata values to hash.
* @param {string} hashAlgorithm - The hashing algorithm to use (e.g., 'sha256', 'md5'). Defaults to 'sha256'.
* @returns {Promise<object>} - An object containing the hashed metadata values. Returns an empty object if metadata is invalid.
* @throws {TypeError} If metadata is not an object or hashAlgorithm is not a string.
*/
async function hashMetadata(metadata, hashAlgorithm = 'sha256') {
if (typeof metadata !== 'object' || metadata === null) {
console.error("Invalid metadata: Metadata must be an object.");
return {};
}
if (typeof hashAlgorithm !== 'string') {
throw new TypeError("hashAlgorithm must be a string.");
}
const crypto = require('crypto'); // Import crypto module
const hashedMetadata = {};
for (const key in metadata) {
if (Object.hasOwnProperty.call(metadata, key)) {
const value = metadata[key];
if (value === null || value === undefined) {
console.warn(`Skipping key '${key}' because its value is null or undefined.`);
continue; // Skip null/undefined values
}
let data;
if (typeof value === 'string') {
data = Buffer.from(value, 'utf8'); // Ensure string is encoded as Buffer
} else if (typeof value === 'number') {
data = Buffer.from(value.toString()); // Convert number to string and then to Buffer
} else if (Array.isArray(value)) {
let arrayString = JSON.stringify(value);
data = Buffer.from(arrayString, 'utf8');
} else if (typeof value === 'object') {
data = JSON.stringify(value)
data = Buffer.from(data, 'utf8');
}
else {
console.warn(`Skipping key '${key}' because its type is not supported.`);
continue;
}
let hash;
try {
if (hashAlgorithm === 'sha256') {
hash = crypto.createHash('sha256').update(data).digest('hex');
} else if (hashAlgorithm === 'md5') {
hash = crypto.createHash('md5').update(data).digest('hex');
} else {
console.warn(`Unsupported hash algorithm: ${hashAlgorithm}. Defaulting to sha256.`);
hash = crypto.createHash('sha256').update(data).digest('hex');
}
} catch (error) {
console.error(`Error hashing value for key '${key}':`, error);
continue;
}
hashedMetadata[key] = hash;
}
}
return hashedMetadata;
}
Add your comment