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
})
}
.
.
.
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)))
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With