/**
* Given an array of characteristics database objects then determine if they are in the same tree;
* @param {*} characteristics[] Database object that represents a characteristic item.
* @returns {boolean} True if all the characteristics are of the same tree
*/
const areCharacteristicsInSameTree = (characteristics) => {
let areInSameTree = false;
areInSameTree = characteristics
.reduce((prev, { dataValues: { tree_id: curr } }) => {
if (!prev.distinctTrees[curr.toString()]) {
prev.distinctTrees[curr.toString()] = 1;
prev.countDistinctTrees += 1;
}
return prev;
},
{ distinctTrees: [], countDistinctTrees: 0 }).countDistinctTrees === 1;
return areInSameTree;
};
/**
* Verify if the names that are specified are scopes that are valid(exists).
* @param {string[]} scopeNames
* @param {*} db Object that will have access to current database.
* @returns {*} Return an object that contains as keys the scopeNames and as value their id.
*/
const validateScopeNames = async (scopeNames, db) => {
let errors = [];
let result = {};
// Determines if the specified scope is valid.
const scopes = await db.scopes.findAll({
where: {
name: scopeNames,
},
});
result = scopes
.reduce((keys, scope) => {
keys[scope.dataValues.name] = scope.dataValues.id;
return keys;
}, {});
errors = errors.concat(
scopeNames
.filter(scopeName => result[scopeName] === undefined)
.map(scopeName => `Invalid Scope: ${scopeName}`),
);
if (errors.length > 0) {
throw errors;
}
return result;
};
/**
* Verify if the names that are specified are existing characteristics.
* @param {string[]} characteristicNames
* @returns {*} Return an object that contains as keys the characetristcNames and as value their id.
*/
const validateCharacteristicNames = async (characteristicNames, db) => {
let errors = [];
let result = {};
// Determines if the specified scope is valid.
const characteristics = await db.characteristics.findAll({
where: {
name: characteristicNames,
},
});
result = characteristics
.reduce((keys, scope) => {
keys[scope.dataValues.name] = scope.dataValues.id;
return keys;
}, {});
errors = errors.concat(
characteristicNames
.filter(characteristicName => result[characteristicName] === undefined)
.map(characteristicName => `Invalid Characteristic: ${characteristicName}`),
);
if (errors.length > 0) {
throw errors;
}
return result;
};
module.exports = {
areCharacteristicsInSameTree,
validateScopeNames,
validateCharacteristicNames,
};
|