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

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

我想做一个 API 有 5 个可选查询参数,我想知道是否有更好的方法来处理这个问题,现在我用 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
   })
}
.
.
.

您可以使用三元运算符在一个查询中完成所有这些操作。如果定义了参数,则检查是否相等,否则就 return 为真。这可能看起来像这样:

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
})

我可能会发现 Lodash 对这个有用:

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

我建议你使用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 });

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