我正在尝试编写几个端点,这些端点将对各种后端服务进行GET和POST http请求,数据格式都非常相似,因此responseHandler函数将被反复复制到不同的路由函数,我想知道是否有办法将responseHandler外部化以便重用。我试图把它移出去,但后来我会失去对res的引用。任何人都有关于更模块化设计的任何提示吗?
routes['/endpoint'] = function(req, res){
console.log("Serving endpoint: /endpoint")
var params={"param": "param-value"}
var options = {
host: 'localhost',
path: '/service?param='+params.param,
method: 'GET'
};
var responseHandler = function(response) {
var data = '';
// keep track of the data you receive
response.on('data', function(chunk) {
data += chunk + "\n";
});
// finished? ok, send the data to the client in JSON format
response.on('end', function() {
res.header("Content-Type:","application/json");
res.end(data);
});
};
// make the request, and then end it, to close the connection
http.request(options, responseHandler).end();
};
答案 0 :(得分:0)
通常我认为你可以在你的lib中创建一个名为responseHandlers的文件夹,添加一个包含类似
的文件var responseHandler = function(response) {
var data = '';
// keep track of the data you receive
response.on('data', function(chunk) {
data += chunk + "\n";
});
// finished? ok, send the data to the client in JSON format
response.on('end', function() {
res.header("Content-Type:","application/json");
res.end(data);
});
};
exports.Handler = responseHandler;
将其保存为whateverHandler.js,然后创建一个index.js文件,该文件需要whatever.js并将其导出为Handler。这样,如果您需要在将来添加更多处理程序,您只需添加文件并更新index.js。使用,在路由处理程序中执行某些操作,如
var handler = require('./lib/responseHandlers').whateverHandler;
routes['/endpoint'] = function(req, res){
console.log("Serving endpoint: /endpoint")
var params={"param": "param-value"}
var options = {
host: 'localhost',
path: '/service?param='+params.param,
method: 'GET'
};
};
// make the request, and then end it, to close the connection
http.request(options, handler).end();
};
答案 1 :(得分:0)
您可以将responseHandler
转换为函数生成器,然后传入res
对象,这样就不会丢失它:
var responseHandler = function(res) {
return function(response) {
var data = '';
// keep track of the data you receive
response.on('data', function(chunk) {
data += chunk + "\n";
});
// finished? ok, send the data to the client in JSON format
response.on('end', function() {
res.header("Content-Type:","application/json");
res.end(data);
});
};
}
并像这样使用它:
routes['/endpoint'] = function(req, res){
console.log("Serving endpoint: /endpoint")
var params={"param": "param-value"}
var options = {
host: 'localhost',
path: '/service?param='+params.param,
method: 'GET'
};
// make the request, and then end it, to close the connection
http.request(options, responseHandler(res)).end();
};