mongoose-management
Version:
Mongoose schemas management tool
79 lines (78 loc) • 2.09 kB
JavaScript
;
/**
* ######################################################################
* # #
* # Do not change the file! #
* # #
* # All changes are deleted the next time the collection data is read. #
* # #
* ######################################################################
*/
Object.defineProperty(exports, "__esModule", { value: true });
/**
*
* @param schema
* @param indexes
*/
exports.addIndexes = (schema, indexes) => {
indexes.forEach(({ fields, options }) => {
schema.index(fields, options);
});
};
/**
*
* @param schema
* @param virtual
*/
exports.addVirtualProperties = (schema, virtual) => {
Object.entries(virtual).forEach(([name, { get, set }]) => {
const space = schema.virtual(name);
if (typeof get === 'function') {
space.get(get);
}
if (typeof set === 'function') {
space.set(set);
}
});
};
/**
*
* @param name
* @param items
*/
exports.checkDuplicateKeys = (name, items) => {
const keys = exports.extractKeys(items);
const duplicates = exports.getDuplicates(keys);
if (duplicates.length > 0) {
throw new Error(`Double keys were assigned in the scheme "${name}": ` + duplicates.join(', '));
}
};
/**
*
* @param items
*/
exports.getDuplicates = (items) => {
const counter = {};
const duplicates = [];
items.forEach((key) => {
if (!counter[key]) {
counter[key] = 1;
}
else {
counter[key] += 1;
}
});
Object.entries(counter).forEach(([key, count]) => {
if (count > 1) {
duplicates.push(key);
}
});
return duplicates;
};
/**
*
* @param items
*/
exports.extractKeys = (items) => {
return items.map((o) => Object.keys(o)).reduce((keys, oKeys) => keys.concat(oKeys), []);
};