如何使用bookhelf根据API url中查询字符串中传递的参数过滤数据?

时间:2016-11-12 15:26:21

标签: javascript node.js rest express bookshelf.js

我使用Bookshelf在Express中创建了REST API,它将所有贡献者的列表提取为JSON

Say API:

GET example.com/contributors

我需要为API制作过滤器和分页, 过滤器选项可以是任何

GET example.com/contributors?status=1&type=pro

因此它将返回状态为1且输入=' pro',

的所有数据

我可以使用where子句

获取此过滤后的数据
Model.Contributors.forge()
.query({where: {status: query_params.status, type: query_params.type}})
.fetch()

我在寻找什么?

但在这里'其中'必须手动指定键值。 由于这些过滤器并不总是固定的,而是取决于客户希望根据需要过滤数据的字段放置的条件,如何使用书架在快递节点api中实现此结构?

这是REST API获取过滤器数据的正确方法,还是根据REST API最佳实践需要实现的其他方式?

代码

路由/ contributors.js

var Contributor_Service = require('./../services/contributor-service');

var express = require('express');
var router = express.Router();

    /* GET all the contributors listing. */
    router.get('/', function (req, res, next) {
        Contributor_Service.listAllContributors(req.query, function (err, data) {
            if (err) {
                res.status(500).json({error: true, data: {message: err.message}});
            } else {
                res.json({error: false, data: data.toJSON()});
            }
        });

    });

module.exports = router;

服务/贡献者-service.js

var Model = require('./../models/Contributor');
var express = require('express');

var listAllContributors = function ( query_params, callback) {

    // for (var x in query_params) {
       // console.log(query_params[x]);
       // console.log(x);
    //}
    Model.Contributors
        .forge()
         .query({where: {status: query_params.status, type: query_params.type}})
        .fetch()
        .then(function (collection) {
            return callback(null, collection);
        })
        .catch(function (err) {
            return callback(err, null);
        });
};

模型/ Contributor.js

var Bookshelf = require('../../dbconfig').bookshelf;

var Contributor = Bookshelf.Model.extend({
    tableName: 'users'
});
var Contributors = Bookshelf.Collection.extend({
    model: Contributor
});

module.exports = {
    Contributor: Contributor,
    Contributors: Contributors
};

1 个答案:

答案 0 :(得分:0)

我使用了where对象,但仍然不确定这是否是编写REST API过滤器的正确方法

因为可以有许多其他查询参数来排序数据,偏移和限制,需要根据查询中传递的条件和字段在控制器中检查和实现。

<强>服务/贡献者-service.js

var Model = require('./../models/Contributor');
var express = require('express');

var listAllContributors = function ( query_params, callback) {

var whereObj = {};

    for (var x in query_params) {
        whereObj[x] =  query_params[x];

    Model.Contributors
        .forge()
        .query({where: whereObj})
        .fetch()
        .then(function (collection) {
            return callback(null, collection);
        })
        .catch(function (err) {
            return callback(err, null);
        });
};