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

时间:2018-08-11 09:02:28

标签: javascript node.js express if-statement query-parameters

我想制作一个具有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
   })
}
.
.
.

3 个答案:

答案 0 :(得分:2)

我可能会发现Lodash对于这一点很有用:

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

答案 1 :(得分:2)

我建议您使用Joi

它是用于JavaScript验证的非常强大的库。您甚至可以使用它进行条件验证。参见complete docs

我在这里为您的方案创建了基本架构。

// validation
const 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 });

其他开发人员也更容易阅读和理解。您可以在整个项目中标准化验证。

答案 2 :(得分:1)

您可以使用三元运算符在一个查询中完成所有这些操作。如果定义了参数,则检查是否相等,否则返回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
})