2016-11-25 71 views
0

使用Sails.js Generate創建API非常簡單。獲取this tutorial example,運行如何自動解析Sails.js路徑上的模型屬性?

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

回報

{ 
    "id": 1, 
    "name": "John Smith", 
    "email" "[email protected]", 
    "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到r esolve像子資源路徑:

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

回答

1

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

配置/ routes.js:

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

API /控制器/ 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 
     }); 
    }); 
}