Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node ExpressJS | How to pass custom query params validation

Learning ExpressJS here. I have a get route that expects query params i.e.


app.get('/api', (req, res) => {
  res.send({ name: req.query.name, age: req.query.age, club: req.query.club })
})

On postman the following http://localhost:5000/api?name=Messi&age=31&club=Barcelona

returns 200 with the res.body as:

{
    "name": "Messi",
    "age": "31",
    "club": "Barcelona"
}

Question

How could I write a custom validation where:

  • If the requested query param doesn't exist: status 400
  • If any of the params are missing i.e (name, age, club) return a response saying that whichever missing param (name, age, and/or age) is required
like image 536
Null isTrue Avatar asked Mar 07 '19 17:03

Null isTrue


1 Answers

You can build an easy validation middleware.

function validateQuery(fields) {

    return (req, res, next) => {

        for(const field of fields) {
            if(!req.query[field]) { // Field isn't present, end request
                return res
                    .status(400)
                    .send(`${field} is missing`);
            }
        }

        next(); // All fields are present, proceed

    };

}

app.get('/api', validateQuery(['name', 'age', 'club']), (req, res) => {
  // If it reaches here, you can be sure that all the fields are not empty.
  res.send({ name: req.query.name, age: req.query.age, club: req.query.club })
})

You can also use a third party module for validating requests.

  • Express Validator
  • Express Superstruct (I'm the author)
like image 197
Marcos Casagrande Avatar answered Sep 28 '22 07:09

Marcos Casagrande