2016-11-25 47 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 
     }); 
    }); 
}