2016-07-12 11 views
1

私は、restra(rest-client)を使用してapiを呼び出して外部apisとデータを取得するsails.jsサービスを持っています。node.jsモジュールのエクスポートで複数のコールバックを統合

モジュールは次のようになり:上記のコードで

var rest = require('restler'); 

module.exports = { 
    config: { 
     url: sails.config.remote_api.base_url.concat('/countries'), 
     rejectUnauthorized: sails.config.remote_api.validateSsl, 
     options: { 'Content-Type': 'application/json' } 
    }, 
    find: function(headers, payload, callback) { 
     var request = rest.get(this.config.url, this.config.options); 
     sails.log.info('Outgoing Request', { log_id: headers[x - request - id], method: request.method, host: request.host, url: request.url }); 

     request.on('2XX', function(data, response) { 
      callback(data, response); 
     }); 
    } 
} 

request.on( '2XX'、...)は、応答コードは200シリーズにあるときに放出されたイベントを処理します。

レスポンスコードが300,400,500シリーズの場合に放出されるイベントの他のハンドラを追加すると、ブロックごとに同じコールバック関数の複製が作成されます。例えば、

var rest = require('restler'); 
module.exports = { 
    config: { 
     url: sails.config.remote_api.base_url.concat('/countries'), 
     rejectUnauthorized: sails.config.remote_api.validateSsl, 
     options: { 'Content-Type': 'application/json' } 
    }, 
    find: function(headers, payload, callback) { 
     var request = rest.get(this.config.url, this.config.options); 
     sails.log.info('Outgoing Request', { log_id: headers[x - request - id], method: request.method, host: request.host, url: request.url }); 

     request.on('2XX', function(data, response) { 
      callback(data, response); 
     }); 

     request.on('3XX', function(data, response) { 
      callback(data, response); 
     }); 

     request.on('4XX', function(data, response) { 
      callback(data, response); 
     }); 

     request.on('5XX', function(data, response) { 
      data = {}; 
      data.succeeded = false; 
      data.failureCode = 'SYSTEM ERROR'; 
      data.failureReason = 'A system error has occurred. Please try again. If the problem persists contact support'; 
      callback(data, response); 
     }); 

     request.on('error', function(data, response) { 
      data.succeeded = false; 
      data.failureCode = 'SERVICE UNAVAILABLE'; 
      data.failureReason = 'The service is temporarily unavailable. Please try again later.'; 
      callback(data, response); 
     }); 
    } 
} 

次の行が重複しないようにするにはどうすればよいですか?

function(data, response) { 
    callback(data, response); 
} 

答えて

1

いいえ、本当にそうすべきではありません。あなたは基本的に2XX3XXなどのような異なるイベントを処理しています。各イベントは別々に処理されており、それは良い習慣です。より単純化すれば、きちんとしたデザインが損なわれる可能性があります。

あなたは直接、非常にcallbackの代わりに、この

request.on('2XX', callback); 
+0

よう

function(data, response) { callback(data, response); } 

感謝を使用することができますが。これにより、コードが大幅に単純化されます。 –

+0

私はupvoteでしたが、私の評判は低く、私のupvoteは表示されていません。 –

+0

別の注記:module.exportsに、繰り返しのコードブロックを持つ複数の関数がDRYの原則に従ってある場合、そのような繰り返しコードをサブ関数に分割する方法2. module.exports内からサブ関数を呼び出す方法 –

関連する問題