簡體   English   中英

如何自動解決Sails.js路線上的模型屬性?

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

使用Sails.js Generate創建API很容易。 獲取本教程示例 ,然后運行

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

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM