Skip to content

Instantly share code, notes, and snippets.

@AndersonZacharyT
Created June 29, 2017 13:30
Show Gist options
  • Save AndersonZacharyT/387bec99bbc8c08d772706da3c23a3a2 to your computer and use it in GitHub Desktop.
Save AndersonZacharyT/387bec99bbc8c08d772706da3c23a3a2 to your computer and use it in GitHub Desktop.
Rules and Helpers
'use strict';
const _ = require('lodash');
/**
* Marks products as highRisk based on stored rules
* stored in db
* @param feed Product object
* @param next Callback
*/
module.exports = (feed, next) => {
getRules((err, docs) => {
if (err) {
return next(err);
} else if (docs.length === 0) {
// No rules no need to process
return next(null, true);
} else {
let isHighRisk = false;
_.forEach(docs, (doc) => {
if (doc.glue === '||') {
isHighRisk = processOr(feed, doc.rules);
} else {
isHighRisk = processAnd(feed, doc.rules);
}
// exit loop if determined high-risk
if (isHighRisk) {
feed.highRiskFlag = true;
feed.riskClassification = doc.riskClassification;
return false;
}
});
next(null, true);
}
});
/**
* caching method to fetch drop fules
* @param cb
*/
function getRules (cb) {
// try cache
let rules = helpers.cacheGet('highRiskRules');
if (rules) {
return cb(null, rules)
}
// Get the rules from persistent datasource
let rulesCollection = config.mongoDb.collection('HighRiskRule');
rulesCollection.find({}, {}).toArray(function (err, docs) {
if (err) {
return cb(err);
}
helpers.cacheSet('highRiskRules', docs);
cb(null, docs);
});
}
/**
* Checks the ors
* @param feed
* @param rules
* @return {boolean}
*/
function processOr (feed, rules) {
let drop = false;
_.forEach(rules, (rule) => {
let regex = new RegExp(rule.value, 'ig');
let value = _.get(feed, rule.key);
if (regex.test(value)) {
drop = true;
return false;
}
});
return drop;
}
/**
* Check the ands
* @param feed
* @param rules
* @return {boolean}
*/
function processAnd (feed, rules) {
let dropEvaluations = [];
_.forEach(rules, (rule) => {
let regex = new RegExp(rule.value, 'ig');
let value = _.get(feed, rule.key);
if (regex.test(value)) {
dropEvaluations.push(true);
}
});
return (dropEvaluations.length === rules.length);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment