Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I want to make a API which have 5 optional query parameters, I want to know if there is a better way to handle this, right now I check each one of them with if conditions, which is kind of dirty! is there any way that I can handle all scenarios without using lot's of if conditions?

let songName = req.query.songName
let singerName = req.query.singerName
let albumName = req.query.albumName
let publishDate = req.query.publishDate

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

if(songName && singerName && albumName && !publishDate) {
   const response = songs.filter(c => { 
      return c.songName === songName && c.singerName === singerName && c.albumName === albumName
   }
   res.send({
      "Data" : response
   })
}

if(songName && singerName && !albumName && publishDate) {
   const response = songs.filter(c => { 
      return c.songName === songName && c.singerName === singerName && c.publishDate === publishDate
   }
   res.send({
      "Data" : response
   })
}

if(songName && !singerName && albumName && publishDate) {
   const response = songs.filter(c => { 
      return c.songName === songName && c.albumName === albumName && c.publishDate === publishDate
   }
   res.send({
      "Data" : response
   })
}

if(!songName && singerName && albumName && publishDate) {
   const response = songs.filter(c => { 
      return c.singerName === singerName && c.albumName === albumName && c.publishDate === publishDate
   }
   res.send({
      "Data" : response
   })
}
.
.
.
like image 409
Emad Dehnavi Avatar asked Aug 11 '18 09:08

Emad Dehnavi


2 Answers

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
})
like image 110
Steffen Schmitz Avatar answered Oct 27 '22 09:10

Steffen Schmitz


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)))
})
like image 28
Anton Harniakou Avatar answered Oct 27 '22 11:10

Anton Harniakou