1

我想在 superagent 的主要功能中添加一些额外的逻辑(日志记录、跟踪内容):https ://github.com/visionmedia/superagent/blob/master/lib/client.js#L444

所以我需要扩展超级代理,并希望提供相同的 API,通过所有功能。我试图通过不同的机制来解决它:Object.create、原型、深拷贝,但我没有让它工作。

我不想操纵 superagent 的源代码,只需要它并包装它,添加我的额外逻辑并调用,通过 origin 函数。我认为这是面向方面的。

// 编辑所以对我不起作用的是绕过请求构造函数:

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);
    }
  });
}
4

2 回答 2

1

您需要发送现有功能

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);
于 2014-09-29T19:56:24.553 回答
1

我几乎可以使用以下代码:

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 相同的 API:var superagent = require("superagent")

但是我不能对 superagent.Request 和 sa.Response 做同样的事情。当我这样做时它不起作用:

superagent.Request.prototype.constructor = function(method, url)
    // my hook
}

还有另一个副作用,如果有没有这个副作用的解决方案就好了:

当需要我的库和超级代理时,超级代理不再是起源,因为我覆盖了超级代理的功能。

于 2014-09-20T20:56:50.917 回答