【问题标题】:How to automatically resolve model attributes on Sails.js routes?如何自动解析 Sails.js 路由上的模型属性?
【发布时间】:2016-11-25 17:29:02
【问题描述】:

使用Sails.js Generate 创建 API 非常简单。获取this tutorial example,运行

curl -X GET http://localhost:1337/employee/1

返回

{
    "id": 1,
    "name": "John Smith",
    "email" "john@email.com",
    "empnum" "123",
    "createdAt" "2015-10-25T19:25:16.559Z",
    "updatedAt" "2015-10-25T19:25:16.559Z",
}

curl -X GET http://localhost:1337/employee/1?fields=name

会回来

{
    "name": "John Smith"
}

我如何配置 Sails.js 来解析子资源路径,而不是传递字段数组:

curl -X GET http://localhost:1337/employee/1/name

【问题讨论】:

    标签: javascript sails.js restful-url yeoman-generator


    【解决方案1】:

    您需要添加自定义路由和控制器功能,例如:

    config/routes.js:

    "GET /employee/:id/:field": "EmployeeController.findOneFiltered"
    

    api/controllers/EmployeeController.js

    findOneFiltered: function(req, res) {
        var id = req.param("id");
        var field = req.param("field");
    
        // Fetch from database by id
        Employee.findOne(id)
        .then(function(employee) {
            // Error: employee with specified id not found
            if (!employee) {
                return res.notFound();
            }
    
            // Error: specified field is invalid
            if (typeof employee[field] === "undefined") {
                return res.badRequest();
            }
    
            // Success: return attribute name and value
            var result = {};
            result[field] = employee[field];
            return res.json(result);
        })
        // Some error occurred
        .catch(function(err) {
            return res.serverError({
                error: err
            });
        });
    }
    

    【讨论】:

      猜你喜欢
      • 2014-12-09
      • 1970-01-01
      • 2016-07-16
      • 2021-10-04
      • 1970-01-01
      • 2014-11-14
      • 2016-01-23
      • 1970-01-01
      • 2019-09-24
      相关资源
      最近更新 更多