Javascript 使用自己的逻辑/旁路构造函数扩展库
我想在superagent的主要功能中添加一些额外的逻辑(日志记录、跟踪内容): 因此,我需要扩展superagent,并希望提供相同的API,即通过所有函数传递的API。我试图通过不同的机制来解决它:Object.create、prototype、deep copy,但我没有让它工作 我不想操纵superagent的源代码,只需要它并包装它,添加我的额外逻辑和调用,通过origin函数传递。我认为它是面向方面的 //编辑 因此,对我来说不起作用的是绕过请求构造函数:Javascript 使用自己的逻辑/旁路构造函数扩展库,javascript,constructor,aop,superagent,Javascript,Constructor,Aop,Superagent,我想在superagent的主要功能中添加一些额外的逻辑(日志记录、跟踪内容): 因此,我需要扩展superagent,并希望提供相同的API,即通过所有函数传递的API。我试图通过不同的机制来解决它:Object.create、prototype、deep copy,但我没有让它工作 我不想操纵superagent的源代码,只需要它并包装它,添加我的额外逻辑和调用,通过origin函数传递。我认为它是面向方面的 //编辑 因此,对我来说不起作用的是绕过请求构造函数: function Requ
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);
}
});
}
我几乎可以用这个代码工作:
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
}
还有另一个副作用,如果有一个没有副作用的解决方案就好了:
当需要my library和superagent时,superagent不再是源,因为我覆盖了superagent的函数。您需要发送现有函数
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);
请显示您尝试过的(全部)代码,而不是(仅)原始构造函数。另外,通过调用包装的构造函数和预期输出的示例,向我们展示您希望在何时添加的额外逻辑。您可以在我提供的链接中看到整个代码(整个文件),带构造函数的行高亮显示。但这是原始代码,不是吗?我的意思是你的方法中那些不起作用的代码:“Object.create,prototype,deep copy”-你做了什么?他们怎么不工作?没有告诉我们要注入哪种逻辑,这甚至不是一个真正的问题。啊,好吧,我只是尝试了
var foo=Object.create(require(“superagent”)
。我取得了一些成功,我将其作为一个答案发布。嘿,你们是如何知道superagent请求中有send方法的?