2016-11-25 6 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例えば、あなたがカスタムルートとコントローラ機能を追加する必要が

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

答えて

1

::のようなサブリソースのパスをesolve

のconfig/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 
     }); 
    }); 
} 
関連する問題