我是nodejs的新手。我正在开发几个apis。我正在使用Sequelize。现在我编写了一个名为buildCriteria的中间件,它为req.query创建了所有实体的where查询。以下是代码:
buildCriteria(req,res,next){
let modeleName = getModelNameFromUrl(req.originalUrl);
let thisModel = models[modelName];
let criteria = {
limit:req.query.limit,
offset:req.query.offset
};
if (req.query.sort && req.query.order){
if (thisModel.tableAttributes[req.query.sort] &&
(req.query.order == 'asc' || req.query.order == 'desc')){
criteria.order = [[req.query.sort, req.query.order]];
}
}
let where = {};
for (var prop in req.query){
if (prop == 'limit' ||
prop == 'offset' ||
prop == 'sort' ||
prop == 'order'){
continue;
}else{
let tProp = thisModel.tableAttributes[prop];
if (tProp){
switch(tProp.type.key){
case 'INTEGER':
where[prop] = parseInt(req.query[prop]);
break;
default:
where[prop] = req.query[prop];
break;
}
}
}
}
criteria.where = where;
req.criteria = criteria;
next();
}
我使用如下:
/*GET ALL*/
router.get('', helper.buildCriteria, async (req, res) => {
let containers =
await
Containers
.findAll(req.criteria)
.catch((err) => {
return responses.Http500(res);
});
return responses.Http200(res, 'all containers', 'containers', containers);
});
这是一个很好的方法,是否有任何其他标准方法来构建通用搜索功能。或者最好为每个搜索组合的每个实体分别编写api(尽管我对此非常怀疑!)