Nodejs - Express - 在 API 中处理可选查询字符串参数的最佳实践

Ema*_*avi 6 javascript if-statement query-parameters node.js express

我想制作一个有 5 个可选查询参数的 API,我想知道是否有更好的方法来处理这个问题,现在我用 if 条件检查每个参数,这有点脏!有什么方法可以在不使用大量 if 条件的情况下处理所有场景?

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
   })
}
.
.
.
Run Code Online (Sandbox Code Playgroud)

Ste*_*itz 2

您可以使用三元运算符在一个查询中完成这一切。如果定义了参数,则检查是否相等,否则返回 true。这可能看起来像这样:

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
})
Run Code Online (Sandbox Code Playgroud)