如何自动解析 Sails.js 路由上的模型属性?

How to automatically resolve model attributes on Sails.js routes?

使用 Sails.js Generate. Getting this tutorial example、运行

创建 API 非常容易
curl -X GET http://localhost:1337/employee/1

returns

{
    "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

会return

{
    "name": "John Smith"
}

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

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

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

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