javorosas
javorosas

Reputation: 769

Filter body of a post request in node.js

Is there a way to simplify this code in node.js + express?

// Backend handler to register a new participant

app.post('/api/participant', function (req, res, next) {
    // I'm catching the registration form from the request
    var data = req.body;

    // I want to make sure the user is not uploading data other
    // than the fields in the form
    var participant = new Participant({
        first: data.first,
        last: data.last,
        email: data.email,
        category: data.category
    });
    participant.save(...);
});

I did not do this:

    var participant = new Participant(data);

Because anyone could include (for example) a score property in the data object and start the competition with an advantage.

So my question is: do I have to do this in every post handler, or is there a way of filtering properties?

Upvotes: 2

Views: 2896

Answers (1)

Dr. McKay
Dr. McKay

Reputation: 2977

A quick Google search didn't find any pre-existing libraries, but this function should do the trick quite nicely:

function filterKeys(object, keys) {
    Object.keys(object).forEach(function(key) {
        if(keys.indexOf(key) == -1) {
            delete object[key];
        }
    });
}

As an example,

var foo = {"foo": 1, "bar": 2, "baz": 3};
console.log(foo); // {"foo": 1, "bar": 2, "baz": 3}
filterKeys(foo, ["foo", "baz"]);
console.log(foo); // {"foo": 1, "baz": 3}

So in your case,

filterKeys(data, ["first", "last", "email", "category"]);

Upvotes: 8

Related Questions