0

I am trying to build a Node.js app using express-validator, which would let me validate a request parameter in the body like so -

req.checkBody('email_id', 'Invalid email ID!').notEmpty().isEmail();

Now I am trying to build one big JSON configuration file which will have all the fields and their rules (which is the function name, like isEmail(), for example) for each route in the application. I want to write to a middleware that intercepts each request, finds out the route, picks up the fields and their validation rules from the JSON file, and then runs those rules. The configuration file would look like this -

{
    "VALIDATION_RULES": {
        "/createUser": {
            "RULES": {
                "email_id": {
                    "message": "Invalid email ID!",
                    "rules": ["notEmpty","isEmail"]
                }
            }
        }
    }
}

I can look into the express-validator module's exports to get all the available validation function names. If they were standalone function calls, I see how I would call the function with just the string of it's name as shown here and here.

How do I pick the rules (notEmpty or isEmail), which are strings in the JSON, turn them into functions and chain them onto req.checkBody($field, $field.message)?

Community
  • 1
  • 1
GPX
  • 3,506
  • 10
  • 52
  • 69

2 Answers2

2

You can use the array notation to call the function.

This should work

req.checkBody($field, $field.message)["notEmpty"]()

or

req.checkBody($field, $field.message)["notEmpty"].apply()

or

req.checkBody($field, $field.message)["notEmpty"].call()

hackerone
  • 315
  • 1
  • 4
2

Just reference the functions using the variable containing the method name:

var fields = {
  "email_id": {
    "message": "Invalid email ID!",
    "rules": ["notEmpty","isEmail"]
  }
};

// ...

var keys = Object.keys(fields);
for (var i = 0, len = keys.length, field, rules; i < len; ++i) {
  field = fields[keys[i]];
  rules = field.rules;
  var checker = req.checkBody(keys[i], field.message);
  for (var f = 0, lenf = rules.length; f < lenf; ++f)
    checker[rules[f]]();
}
mscdex
  • 104,356
  • 15
  • 192
  • 153