我想添加一些额外的逻辑(记录,跟踪内容)到superagent的主要功能:https://github.com/visionmedia/superagent/blob/master/lib/client.js#L444
所以我需要扩展superagent,并希望提供相同的API,通过所有功能。我尝试通过不同的机制解决它:Object.create,prototype,deep copy,但我没有让它工作。
我不想操纵superagent的源代码,只需要它并包装它,添加我的额外逻辑并调用,直接通过origin函数。我认为这是面向方面的。
//编辑 所以对我不起作用的是绕过Request构造函数:
function Request(method, url) {
var self = this;
Emitter.call(this);
this._query = this._query || [];
this.method = method;
this.url = url;
this.header = {};
this._header = {};
this.on('end', function(){
try {
var res = new Response(self);
if ('HEAD' == method) res.text = null;
self.callback(null, res);
} catch(e) {
var err = new Error('Parser is unable to parse the response');
err.parse = true;
err.original = e;
self.callback(err);
}
});
}
答案 0 :(得分:0)
我几乎使用了这段代码:
var superagent = require('superagent');
var uuid = require('uuid');
var map = {};
var init = function() {
var supderdebug = function(method, url) {
console.log("pass through: root");
return superagent.apply(this, arguments);
}
var methods = ['get', 'head', 'del', 'patch','post', 'put'];
methods.forEach(function(method) {
var origin = superagent[method];
supderdebug[method] = function(url) {
console.log("pass through: "+method+"('"+url+"')");
var request = origin.apply(this, arguments);
var id = uuid();
map[id] = request;
return request;
}
});
_end = superagent.Request.prototype.end;
superagent.Request.prototype.end = function(fn) {
console.log("pass through: end");
return _end.apply(this, arguments);
}
_callback = superagent.Request.prototype.callback;
superagent.Request.prototype.callback = function(err, res) {
console.log("pass through: callback");
if (err) {
console.log(err);
}
var response = _callback.apply(this, arguments);
return response;
}
return supderdebug;
}
module.exports.init = init
用法:
var sd = require("supderdebug").init();
然后,当我需要时,我会获得与superagent相同的API:var superagent = require("superagent")
但我不能对superagent.Request和sa.Response做同样的事。当我这样做时,它不起作用:
superagent.Request.prototype.constructor = function(method, url)
// my hook
}
还有另一个副作用,如果有一个没有这种副作用的解决方案会很好:
当要求我的图书馆和superagent时,superagent不再是原点,因为我覆盖了superagent的功能。
答案 1 :(得分:0)
您需要发送现有功能
superagent.Request.prototype.end = function(end) {
return function() {
console.log("before end");
var request = end.apply(this, arguments);
console.log("after end");
return request;
};
}(superagent.Request.prototype.end);