我正試圖在npm包中重載/替換函數。該軟件包被創建用來與星號AMI(一個套接字接口)進行對話。在公共npm包中修改某些功能
我需要與具有幾乎完全相同接口的服務通話,但它在登錄時顯示不同的歡迎字符串,並且它在登錄時需要額外的字段。其餘的都是一樣的。我不想簡單複製600 LOC,而是修改兩行或三行,我想覆蓋檢測問候字符串和登錄功能的函數,並繼續使用包。
裏面ami-io
包有一個文件index.js
包含以下功能:
Client.prototype.auth = function (data) {
this.logger.debug('First message:', data);
if (data.match(/Asterisk Call Manager/)) {
this._setVersion(data);
this.socket.on('data', function (data) {
this.splitMessages(data);
}.bind(this));
this.send(new Action.Login(this.config.login, this.config.password), function (error, response) {
if (response && response.response === 'Success') this.emit('connected');
else this.emit('incorrectLogin');
}.bind(this));
} else {
this.emit('incorrectServer', data);
}
};
現在我想不匹配Asterisk Call Manager
,但MyService
,我要定義和使用Action.LoginExt(this.config.login, this.config.password)
與另一個帶有一個額外的參數。
這可能嗎?我在我自己的模塊嘗試這樣做:
var AmiIo = require('ami-io');
var amiio = AmiIo.createClient({port:5038, host:'x.x.x.x', login:'system', password:'admin'});
amiio.prototype.auth = function (data) {
this.logger.debug('First message:', data);
if (data.match(/MyService Version/)) {
this._setVersion(data);
this.socket.on('data', function (data) {
this.splitMessages(data);
}.bind(this));
this.send(new Action.LoginExt(this.config.login, this.config.password, this.config.extra), function (error, response) {
if (response && response.response === 'Success') this.emit('connected');
else this.emit('incorrectLogin');
}.bind(this));
} else {
this.emit('incorrectServer', data);
}
};
...但它造成了TypeError: Cannot set property 'auth' of undefined
,現在我無言以對。 另外,我可以在自己的模塊中定義一個新的Action.LoginExt
對象嗎?怎麼樣?
的action.js模塊定義的Action對象如下:
function Action(name) {
Action.super_.bind(this)();
this.id = this.getId();
this.set('ActionID', this.id);
this.set('Action', name);
}
(function(){
var Message = require('./message.js');
var util = require('util');
util.inherits(Action, Message);
})();
Action.prototype.getId = (function() {
var id = 0;
return function() {
return ++id;
}
})();
function Login(username, secret) {
Login.super_.bind(this, 'Login')();
this.set('Username', username);
this.set('Secret', secret);
}
... more functions ...
(function() {
var actions = [
Login,
... more functions ...
];
var util = require('util');
for (var i = 0; i < actions.length; i++) {
util.inherits(actions[i], Action);
exports[actions[i].name] = actions[i];
}
exports.Action = Action;
})();
我想我明白的是,行動是從信息的子類。 Login函數依次從Action繼承,並導出(在最後一個代碼塊中)。 所以我覺得在我的代碼,我可以嘗試類似的東西:
// extend ami-io with LoginExt function
function LoginExt(username, secret, company) {
Login.super_.bind(this, 'LoginExt')();
this.set('Username', username);
this.set('Secret', secret);
this.set('Company', company);
}
var util = require('util');
util.inherits(LoginExt, amiio.Action);
但util.inherits失敗,不確定的。我也在ami-io上開了一個問題。
謝謝。這很簡單。我現在只剩下添加/擴展Action的角色了。修改模塊本身可能確實比較簡單,但是我必須將其引入我自己的代碼庫中,這會產生技術債務。或者......分叉它,重命名它,並將其放入npm回購。只有幾行代碼... – raarts