|
| 1 | +/** |
| 2 | + * Formats mongoose errors into proper array |
| 3 | + * |
| 4 | + * @param {Array} errors |
| 5 | + * @return {Array} |
| 6 | + * @api public |
| 7 | + */ |
| 8 | + |
| 9 | +exports.errors = function (errors) { |
| 10 | + var keys = Object.keys(errors) |
| 11 | + var errs = [] |
| 12 | + |
| 13 | + // if there is no validation error, just display a generic error |
| 14 | + if (!keys) { |
| 15 | + return ['Oops! There was an error'] |
| 16 | + } |
| 17 | + |
| 18 | + keys.forEach(function (key) { |
| 19 | + errs.push(errors[key].message) |
| 20 | + }) |
| 21 | + |
| 22 | + return errs |
| 23 | +} |
| 24 | + |
| 25 | +/** |
| 26 | + * Index of object within an array |
| 27 | + * |
| 28 | + * @param {Array} arr |
| 29 | + * @param {Object} obj |
| 30 | + * @return {Number} |
| 31 | + * @api public |
| 32 | + */ |
| 33 | + |
| 34 | +exports.indexof = function (arr, obj) { |
| 35 | + var index = -1; // not found initially |
| 36 | + var keys = Object.keys(obj); |
| 37 | + // filter the collection with the given criterias |
| 38 | + var result = arr.filter(function (doc, idx) { |
| 39 | + // keep a counter of matched key/value pairs |
| 40 | + var matched = 0; |
| 41 | + |
| 42 | + // loop over criteria |
| 43 | + for (var i = keys.length - 1; i >= 0; i--) { |
| 44 | + if (doc[keys[i]] === obj[keys[i]]) { |
| 45 | + matched++; |
| 46 | + |
| 47 | + // check if all the criterias are matched |
| 48 | + if (matched === keys.length) { |
| 49 | + index = idx; |
| 50 | + return idx; |
| 51 | + } |
| 52 | + } |
| 53 | + }; |
| 54 | + }); |
| 55 | + return index; |
| 56 | +} |
| 57 | + |
| 58 | +/** |
| 59 | + * Find object in an array of objects that matches a condition |
| 60 | + * |
| 61 | + * @param {Array} arr |
| 62 | + * @param {Object} obj |
| 63 | + * @param {Function} cb - optional |
| 64 | + * @return {Object} |
| 65 | + * @api public |
| 66 | + */ |
| 67 | + |
| 68 | +exports.findByParam = function (arr, obj, cb) { |
| 69 | + var index = exports.indexof(arr, obj) |
| 70 | + if (~index && typeof cb === 'function') { |
| 71 | + return cb(undefined, arr[index]) |
| 72 | + } else if (~index && !cb) { |
| 73 | + return arr[index] |
| 74 | + } else if (!~index && typeof cb === 'function') { |
| 75 | + return cb('not found') |
| 76 | + } |
| 77 | + // else undefined is returned |
| 78 | +} |
0 commit comments