Nodejs - Express - Best practice to handle optional query-string parameters in API Nodejs - Express - Best practice to handle optional query-string parameters in API express express

Nodejs - Express - Best practice to handle optional query-string parameters in API


You could use the ternary operator to do this all in one query. If the parameter is defined you check for equality and else you just return true. This could look like this:

const response = songs.filter(c => {    return (songName ? (c.songName === songName) : true) &&           (singerName ? (c.singerName === singerName) : true) &&           (albumName ? (c.albumName === albumName) : true);});res.send({    "Data": response})


I may find Lodash to be useful for this one:

const response = songs.filter(song => {   return _.isEqual(req.query, _.pick(song, Object.keys(req.query)))})


I suggest you to use Joi

It is very powerful library for javascript validations. You can make even conditional validations using it. See the complete docs.

I created basic schema for your scenario here.

// validationconst schema = Joi.object().keys({    songName: Joi.string()    singerName: Joi.string()    albumName: Joi.string()    publishDate: Joi.date()});const { error, value } = Joi.validate(req.query, schema, { abortEarly: false, allowUnknown: false });if (error !== null) return res.send(400, { code: 400, message: "validation error", error: error.details });

It is easier to read and understand for other developers too. You can standardized the validations in the overall project.