2016-09-13 3 views
1

find 청사진 결과에 몇 가지 추가 데이터를 추가해야합니다. 내가 여기에 응답을 변경하거나 청사진에 콜백을 추가 할 수있는 방법을 찾을은`t돛 청사진 수명주기

module.exports = { 
    find: function(req, res) { 
    return sails.hooks.blueprints.middleware.find(req, res); 
    } 
} 

하지만 :이 솔루션을 발견했다.

module.exports = function findRecords (req, res, cb) { 
    ... 
    if (typeof cb === 'function') res.ok(cb(result)); 
    else res.ok(result); 

을하지만,이 경우에는 500에 statusCode 때마다 (단, 해당 데이터 포함) 만 복사 - 붙여 넣기 솔루션이 존재처럼

+0

달성하고자하는 목표는 무엇입니까? 응답이나 헤더에 데이터를 추가 하시겠습니까? 콜백을 왜 추가하고 있습니까? –

+0

@zabware 청사진 결과에 통계 정보 (관련 테이블 수)를 추가하고 싶습니다. 나는 이것을 여러 컨트롤러에서 필요로하기 때문에'find' 청사진의 코드를 복사/붙여 넣기 만하면됩니다. – Crusader

+0

관련 테이블에서 정보를 채우는 것은 쉽습니다. 먼저 테이블이 실제로 연결되어 있는지 확인하십시오 (예 : models/Article.js : module.exports.attributes {..., user = {model : 'User'}}) 둘째 :'sails.config. blueprints.populate'는 true로 설정됩니다. http://sailsjs.com/documentation/reference/blueprint-api/populate-where – qualbeen

답변

0

이 보인다을 반환 : 난 청사진을 변경하고있는 CB를 추가하려고합니다. 그래서 node_modules/sails/lib/hooks/blueprints/actions 파일의 모든 코드를 모든 컨트롤러의 작업으로 복사 한 다음 변경합니다.

1

저는 몇 시간 동안 동일한 문제로 고심하고 있습니다. 여기이 문제를 해결하기 위해 해킹 (해명)이 있습니다.

오류가 발생하면 청사진을 작성하면 항상 res.ok, res.notFound 또는 res.serverError가 호출됩니다. 이 메서드 호출을 변경하면 출력을 수정할 수 있습니다.

module.exports.find = function (req, res) { 

    var override = {}; 
    override.serverError = res.serverError; 
    override.notFound = res.notFound; 
    override.ok = function (data) { 

     console.log('overriding default sails.ok() response.'); 
     console.log('Here is our data', data); 

     if (Array.isArray(data)) { 
      // Normally an array is fetched from the blueprint routes 
      async.map(data, function(record, cb){ 

       // do whatever you would like to each record 
       return cb(null, record); 

      }, function(err, result){ 
       if (err) return res.error(err); 
       return res.ok(result); 
      }); 
     } 
     else if (data){ 
      // blueprint `find/:id` will only return one record (not an array) 
      data.foo = 'bar'; 
      return res.ok(data); 
     } 
     else { 
      // Oh no - no results! 
      return res.notFound(); 
     } 
    }; 

    return sails.hooks.blueprints.middleware.find(req, override); 
}; 
+0

고맙습니다. res에서 직접 ok 메서드를 재정의 할 수 있습니까? 'res.ok = function (data) {...}; return sails.hooks.blueprints.middleware.find (req, res); ' – Crusader

+0

예 @Crusader,이게 더 좋은 생각 같네요! 이 방법으로'res' 객체에 대한 다른 의존성은 여전히 ​​유효합니다. (하지만 실제로 제안을 테스트하지 않았습니다.) – qualbeen