UNPKG

node-rigorous

Version:
52 lines (34 loc) 1.59 kB
/* eslint no-param-reassign:0 */ const mongoose = require('mongoose'); const helperFormatChecker = require('../../helpers/format_checker'); module.exports = (schema, modelName, attributesSettings) => { const primaryKeyAttributes = []; const indexPrimaryKey = {}; let partialKey = false; Object.keys(attributesSettings).forEach((attribute) => { const attributeObject = attributesSettings[attribute]; if (attributeObject.partialPrimaryKey) { partialKey = true; primaryKeyAttributes.push(attribute); indexPrimaryKey[attribute] = 1; } }); if (partialKey) { schema.index(indexPrimaryKey, { unique: true }); const validateObject = { validator: (v) => { const queryPrimaryKeys = {}; primaryKeyAttributes.forEach((attribute) => { queryPrimaryKeys[attribute] = v[attribute]; }); return new Promise(((resolve, reject) => { mongoose.model(modelName).findOne(queryPrimaryKeys).select('_id').exec() .then((result) => { resolve(helperFormatChecker.isNil(result)); }) .catch((err) => { reject(err); }); })); }, message: props => `${props} has violated primarykey unicity validation`, }; primaryKeyAttributes.forEach((attribute) => { attributesSettings[attribute].schema.validate.push(validateObject); }); } };