UNPKG

node-rigorous

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