Modifying some features in a public npm package - javascript

I am trying to overload/replace functions in the ami-io npm package. That package is created to talk to asterisk AMI, a socket interface.
I need to talk to a service that has almost the exact same interface, but it presents a different greeting string upon login, and it requires an extra field in the logon. All the rest is the same. Instead of just plain copying the 600 LOC ami-io package, and modifying two or three lines, I want to override the function that detects the greeting string, and the login function, and keep using the ami-io package.
Inside the ami-io package there is a file index.js which contains the following function:
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);
}
};
Now I want to match not on Asterisk Call Manager, but on MyService, and I want to define and use Action.LoginExt(this.config.login, this.config.password) with another one with an extra parameter.
Is this possible? I tried this in my own module:
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);
}
};
...but it resulted in TypeError: Cannot set property 'auth' of undefined, and now I am clueless.
Also, can I define a new Action.LoginExt object in my own module? How?
The action.js module defines the Action objects as follows:
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;
})();
What I think I understand is that Action is subclassed from Message. The Login function in its turn is subclassed from Action, and exported (in the last code block).
So I think in my code I could try something similar:
// 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);
But util.inherits fails with undefined. I've also opened a issue on ami-io.

You can use:
var AmiIo = require('ami-io');
AmiIo.Action.Login = function NewConstructor(){}; //to override Login action
//new constructor shold extend AmiIo.Action.Action(actionName)
//and also, you can use
AmiIo.Action.SomeNewAction = function SomeNewAction(){};//to create new actuion
//it also should extend AmiIo.Action.Action(actionName);
AmiIo.Action is just an Object. All constructors are fields of it.
To create new events you don't need to do anything, because it is just an object. If server send to you
Event: Armageddon
SomeField: 123
ami-io will create event with name 'Armageddon'.
To override Client#auth() method, you just should do
var AmiIo = require('ami-io');
AmiIo.Client.prototype.auth = function (){};//new function

amiio is an instance of a Client. The prototype property is only meaningful on constructor functions, such as Client. It is not meaningful on the result of a constructor function (except in the uncommon case that the instance happens to also be a function itself -- but even in that case, altering the instance's prototype does not influence its parent constructor).
Instead, you need to get the instance's prototype with Object.getPrototypeOf:
Object.getPrototypeOf(amiio).auth = function() { ... }
If you don't need to change this for every client, but only a single client, you don't need to change the prototype at all. Changing the instance's auth is sufficient:
amiio.auth = function() { ... }
Note that you code will not work if Action.LoginExt is local to the module scope. If the module exports it, you can probably do AmiIo.Action.LoginExt instead. If it does not export LoginExt, you will need to copy the code that implements it a re-implement it in your importing scope. It may be simpler to modify the module itself.

Here's the solution I applied that worked:
// Override the AmiIo auth procedure, because the other login is slightly different
// Write our own Login function (which adds a company)
function Login(username, secret, company) {
Login.super_.bind(this, 'Login')();
this.set('Username', username);
this.set('Secret', secret );
this.set('Company', company);
}
// This function should inherit from Action
var util = require('util');
util.inherits(Login, AmiIo.Action.Action);
AmiIo.Action.Login = Login;
// replace the auth with our own, to add the company. Also
// this sends a slightly different greeting: "Service Version 1.0"
AmiIo.Client.prototype.auth = function (data) {
if (data.match(/Service Version/)) {
this._setVersion(data);
this.socket.on('data', function (data) {
this.splitMessages(data);
}.bind(this));
this.send(new AmiIo.Action.Login(this.config.login, this.config.password, this.config.company), function (error, response) {
if (response && response.response === 'Success') this.emit('connected');
else this.emit('incorrectLogin');
}.bind(this));
} else {
this.emit('incorrectServer', data);
}
};
// our own function to grab the version number from the new greeting
AmiIo.Client.prototype._setVersion = function(version){
var v = version.match(/Service Version ([\d\.]*[\-\w\d\.]*)/i);
if (v){
this.version = v[1];
}
};
So it turns out this was as doable as I hoped it would be. Both answers by #NumminorihSF and #apsillers helped me here, but I could mark only one of them as the best answer.

Related

Confusion on how to work with module pattern

I am confused on how to work with module pattern (and design patterns in general) in JavaScript.
I already wrote some functioning code in my application using module pattern that does what I want to, but it doesn't seem to be very modular to me, and I keep having this feeling that I am doing it wrong. I didn't manage to find any concrete and complete application example with any design pattern.
Here is how I work with it :
Let's say I have forms in my application that I'll use for different modules (post a thread, reply to a thread, comment the guests book), with some JavaScript I'll give users some functionalities, as such as popping a smiley bubble and handling insertion of them in my forms, sending data posts to my server code to return the HTML code in order to add the message without reloading the page, I'll do something like that:
let Form = function (selector_form, selector_textarea, selector_emoticonsButton, selector_postButton) {
let form, textarea, emoticonsButton, postButton;
let emoticonsBubble = new EmoticonsBubble()
return {
selectors: function () {
return {
form: function () { return selector_form },
sendButton: function () { return selector_sendButton }
}
}
setElements: function (obj) {
form = $(obj).get(0);
textarea = $(form).find(selector_textarea).get(0);
emoticonsButton = $(form).find(emoticonsButton).get(0);
postButton = $(form).find(selector_postButton).get(0);
emoticonsBubble.setElements(form, emoticonsButton);
},
get: function () {
return {
form: function () { return form },
//...
emoticonsBubble: function () { return emoticonsBubble }
}
},
post: function (moduleId, callback) {
$.ajax({
//parameters
}).done(function (data) {
callback(data);
});
}
}
}
let EmoticonsBubble = function () {
let thisContainerToAppendTo, thisTextarea;
return {
setElements: function (container, textarea) {
thisContainerToAppendTo = container;
thisTextarea = textarea;
},
pop: function () {
this.ajax().pop(function (data) {
$(thisContainerToAppendTo).append(data);
});
}
insert: function (emoticon) {
$(thisTextarea).append(emoticon);
},
ajax: function () {
return {
pop: function (callback) {
$.ajax({
//parameters
}).done(function (data) {
callback(data);
});
}
}
}
}
}
// Events part
let form = new Form('#threadForm', '.textarea', 'button[name="emoticons"]', 'button[name="send"]');
let emoticonsBubble = form.get().emoticonsBubble();
$(form.selectors().form()).on('click', function (e) {
form.setElements(this);
});
$(form.selectors().sendButton()).on('click', function (e) {
let moduleId = // retrieve module id, if it belongs to guests book, thread creation module or reply module
form.post(moduleId, function (data) {
// append data to something
});
});
// etc for emoticons handling
The fact that I have to rewrite the event part for every different form I have in my application while keeping everything the same but variables name, annoys me a lot.
Could you guys tell me how you would handle those functionalities and what may be wrong with my way of coding?
The Module Pattern is about keeping units of code from colliding with other scopes (usually the Global scope).
As we know, in JavaScript, variables defined with:
let and const are scoped to their parent block
var are scoped to their containing function (or Global if not in a
function)
So, if you were to take your Form function:
let Form = function (x,y,z) {
let form, textarea, emoticonsButton, postButton;
let emoticonsBubble = new EmoticonsBubble()
return {
. . .
}
setElements: function (obj) {
. . .
},
get: function () {
. . .
},
post: function (moduleId, callback) {
. . .
}
}
}
The variable Form is Global because there is no containing block. This is a problem because what if there is already another Global called Form (which there very well could be because of the generic nature of the word "Form"). So, this code doesn't cut off your code from being exposed. To use the Module Pattern on it, we'd wrap it with an IIFE (Immediately Invoked Function Expression) and within that IIFE, we'd create a custom namespace in the Global scope that we're sure doesn't exist (thereby avoiding name collisions):
(function(){
// This is going to be exposed as publicly available via the module namespace
function Form(x,y,z) {
. . .
}
// This will remain private within the module
function helper(){
}
// **********************************************************************
let temp = {}; // Create a temporary object to bind only the public API
temp.Form = Form; // Bind the public members to the object
// Expose the module to the Global scope by creating a custom namespace
// and mapping the temp object to it
window.myCustomAPI = temp;
})();
// Now, outside of the module (in some higher scope), your public portions
// of the Module are accessible:
let myForm = new myCustomAPI.Form(arg, arg, arg);
The repetition in your code basically comes from the selection of elements and their helpers, and that can easily be abstracted into a function:
function Elements(selectors, children, options) {
let elements = { ...children };
return {
selectors,
elements,
setElements(obj) {
for(const [name, selector] of Object.entries(selectors))
elements[name] = $(obj).find(selector).get(0);
for(const child of Object.values(child))
child.parent && child.parent(this, obj);
},
...options
}
}
That can then be used as:
function Form(form, textarea, emoticonsButton, postButton) {
const emoticonsBubble = EmoticonsBubble();
return Elements({ form, textarea, emoticonButtons }, { emoticonsBubble }, {
post() {
//...
}
});
}
function EmoticonsBubble() {
return Elements({ /*...*/ }, {}, {
parent(parent, obj) {
this.setElements(parent);
}
});
}
But you are basically reinventing a lot of wheels here, have you thought about using one of the MVCs that are out there (React, Vue, ...) ?
Ok the boilerplate for some common tasks that you have in the event part is driving you crazy right ?
So checking your code you can fix them in many ways.
A. Encapsulate your code in real modules I mean this.
const Form = (function(/*receive here dependencies as arguments */){
// your code module goes here
})(/*inject dependencies here to module*/);
B. You can create a event pattern module, to drive your internal and externals events for module.
C. You know what are the listener that the module needs , so apply them into your module.
That way should be more reusable than now

Function chaining with function names from list [duplicate]

What is the equivalent code of window["functionName"](arguments) in NodeJS server-side?
If you need such a capability within a module, one hack is to store such module functions in variables within the module and then call them by accessing them from the module object properties. Example:
var x = { }; // better would be to have module create an object
x.f1 = function()
{
console.log('Call me as a string!');
}
Now, within the module, you can call it using the value from a string:
var funcstr = "f1";
x[funcstr]();
I am learning the ropes with Node myself, the above is probably all sorts of wrong :-). Perhaps a marginally better way to write this example would be (for the module m.js):
module.exports =
{
f1: function() { console.log("Call me from a string!"); },
f2: function(str1) { this[str1](); }
}
Now you can:
var m = require('m.js');
m.f2('f1');
Or even just:
var m = require('m.js');
m['f1']();
FWIW!
you're looking for global
Note, however, that in modules nothing is ever exposed to this level
1) If methods are in same js file
define all methods as properties of Handler:
var Handler={};
Handler.application_run = function (name) {
console.log(name)
}
Now call it like this
var somefunc = "application_run";
Handler[somefunc]('jerry codes');
Output: jerry codes
2) If you want to keep methods in a different js file
// Handler.js
module.exports={
application_run: function (name) {
console.log(name)
}
}
Use method defined in Handler.js in different.js:
// different.js
var methods = require('./Handler.js') // path to Handler.js
methods['application_run']('jerry codes')
Output: jerry codes
If you want to call a class level function using this then following is the solution and it worked for me
class Hello {
sayHello(name) {
console.log("Hello " + name)
}
callVariableMethod() {
let method_name = 'sayHello'
this[`${method_name}`]("Zeal Nagar!")
}
}
If You need it in module scope, You can use something like this
var module = require('moduleName');
module['functionName'](arguments);
Honestly, looking at all these answers they seem a bit too much work. I was playing around to look for other ways around this. You can use the eval() command to print a variable as text then call it as a function
I.e
let commands = ['add', 'remove', 'test'];
for (i in commands) {
if (commands[i] == command) {
var c = "proxy_"+command;
eval(c)(proxy);
}
}
eval(string)(arg1, arg2);
This example script would execute the function proxy_test(proxy)
You know, the OP's code inspired me to try this:
global.test = function(inVal){
console.log(inVal);
}
global['test']('3 is the value')
But now that I think about it, it's no better than #Ravi' s answer.
I use this for node, see if this approach works for you
var _ = require('lodash');
var fnA1 = require('functions/fnA1');
var fnA2 = require('functions/fnA2');
module.exports = {
run: function(fnName, options, callback) {
'use strict';
var nameSpace = fnName.toString().split('.');
// if function name contains namespace, resolve that first before calling
if (nameSpace.length > 1) {
var resolvedFnName = this;
_.forEach(nameSpace, function(name){
resolvedFnName = resolvedFnName[name];
});
resolvedFnName(options, callback);
} else {
this[fnName](options, callback);
}
},
fnA1: fnA1,
fnA2: fnA2
};
call this like
importVariable.run('fnA1.subfunction', data, function(err, result){
if (err) {return callback(err);}
return callback(null, result);
});
That is not specific to the window object. In JavaScript any property of the object can be accessed this way. For example,
var test = {
prop1 : true
};
console.log(test.prop1); // true
console.log(test["prop1"]); // also true
Read more here : https://developer.mozilla.org/en/JavaScript/Guide/Working_with_Objects

node.js automatic logging with metadata

I want to create a Node.js logged decorator (function filter) that works like this (pseudocode warning):
logged = function(f) {
return function() {
log(f.file, f.line, f.class, f.name, arguments)
return f.call(this, arguments)
}
}
Is there a way of accesing the information above? I'm going to be doing heavy logging, so throwing a fake Exception and reading the trace is probably not viable (or is it?).
Note: by f.class I mean the name of the function that holds the prototype. Also, I'm using coffee-script, in case it matters
You don't have to throw the exception, var stack = new Error().stack is enough. From there it is possible to parse out the file, line number, and the class name. BUT the problem is, that it only tracks the function calls, so now to get the proper information for the decorated function Error should be initialized some where within the function or the class. Doing this in decorator, you can get only the information about the file/linenumber where the decoration of the function was occurred, and not where the function was declared.
function User(){}
User.prototype.foo = function(){};
User.stack_ = function(){
return new Error().stack
};
// ...
function wrapp(Ctor, name){
var stack = Ctor.stack_();
var info = parseStack(stack);
var orig_ = Ctor.prototype[name];
Ctor.prototype[name] = function(){
console.log('Info:', info);
return orig_.apply(this, arguments);
};
}
function parseStack(stack){
// implement better stacktrace parser
return stack.split('\n')[1];
}
// ...
wrapp(User, 'foo');
// ...
var user = new User;
user.foo();
// and you get smth. like
// Info: at Function.User.stack_ (filename:line:column)
I think this is maximum you can get, and you must always define this stack_ function.

Simple node.js module with init method

I'm trying to sort out a good simple pattern for node.js with an init method for the use of 'models' when connecting to mongodb collections. Basically, each collection has a 'model'.
Here's what I have, setup as a singleton, any reason not go to with this method or is there more recommended method within the context of node?
module.exports = User;
function User () {
if ( arguments.callee.instance ) {
return arguments.callee.instance;
} else {
arguments.callee.instance = this;
}
//Init our database collection
}
User.findOne = function (user_id) {
}
User.addUser = function () {
}
return new User();
Thank you!
Um, you should put User.prototype.method.
User.prototype.findOne = function (user_id) {
}
User.prototype.addUser = function () {
}
Instead of 'return new User()' you probably meant,
module.exports = new User();
One reason not to export a 'new' User() is if you want to create more than one user in your nodejs program. If you only have one user, then a singleton is fine. Also, if you want to pass data to this module, you may want to do so via a constructor argument, and if you only construct the User in the module, then you can't pass to the constructor in your app.
I use a pattern that assigns module.exports to a function. The first argument of all my exports is an object shared amongst all exports, so they can add events/listeners and talk to each other in various different ways.
For example ('events' and 'app' are psuedo, not based on any real API),
function doLogin(app) {
return function (e) {
// some code to do login
}
}
module.exports = function login (app) {
app.events.on('login', doLogin(app));
}
Now all of the other modules can trigger a login via
app.events.login({'user': '..','pass': '..'});

Equivalent of "window["functionName"](arguments)" in server-side

What is the equivalent code of window["functionName"](arguments) in NodeJS server-side?
If you need such a capability within a module, one hack is to store such module functions in variables within the module and then call them by accessing them from the module object properties. Example:
var x = { }; // better would be to have module create an object
x.f1 = function()
{
console.log('Call me as a string!');
}
Now, within the module, you can call it using the value from a string:
var funcstr = "f1";
x[funcstr]();
I am learning the ropes with Node myself, the above is probably all sorts of wrong :-). Perhaps a marginally better way to write this example would be (for the module m.js):
module.exports =
{
f1: function() { console.log("Call me from a string!"); },
f2: function(str1) { this[str1](); }
}
Now you can:
var m = require('m.js');
m.f2('f1');
Or even just:
var m = require('m.js');
m['f1']();
FWIW!
you're looking for global
Note, however, that in modules nothing is ever exposed to this level
1) If methods are in same js file
define all methods as properties of Handler:
var Handler={};
Handler.application_run = function (name) {
console.log(name)
}
Now call it like this
var somefunc = "application_run";
Handler[somefunc]('jerry codes');
Output: jerry codes
2) If you want to keep methods in a different js file
// Handler.js
module.exports={
application_run: function (name) {
console.log(name)
}
}
Use method defined in Handler.js in different.js:
// different.js
var methods = require('./Handler.js') // path to Handler.js
methods['application_run']('jerry codes')
Output: jerry codes
If you want to call a class level function using this then following is the solution and it worked for me
class Hello {
sayHello(name) {
console.log("Hello " + name)
}
callVariableMethod() {
let method_name = 'sayHello'
this[`${method_name}`]("Zeal Nagar!")
}
}
If You need it in module scope, You can use something like this
var module = require('moduleName');
module['functionName'](arguments);
Honestly, looking at all these answers they seem a bit too much work. I was playing around to look for other ways around this. You can use the eval() command to print a variable as text then call it as a function
I.e
let commands = ['add', 'remove', 'test'];
for (i in commands) {
if (commands[i] == command) {
var c = "proxy_"+command;
eval(c)(proxy);
}
}
eval(string)(arg1, arg2);
This example script would execute the function proxy_test(proxy)
You know, the OP's code inspired me to try this:
global.test = function(inVal){
console.log(inVal);
}
global['test']('3 is the value')
But now that I think about it, it's no better than #Ravi' s answer.
I use this for node, see if this approach works for you
var _ = require('lodash');
var fnA1 = require('functions/fnA1');
var fnA2 = require('functions/fnA2');
module.exports = {
run: function(fnName, options, callback) {
'use strict';
var nameSpace = fnName.toString().split('.');
// if function name contains namespace, resolve that first before calling
if (nameSpace.length > 1) {
var resolvedFnName = this;
_.forEach(nameSpace, function(name){
resolvedFnName = resolvedFnName[name];
});
resolvedFnName(options, callback);
} else {
this[fnName](options, callback);
}
},
fnA1: fnA1,
fnA2: fnA2
};
call this like
importVariable.run('fnA1.subfunction', data, function(err, result){
if (err) {return callback(err);}
return callback(null, result);
});
That is not specific to the window object. In JavaScript any property of the object can be accessed this way. For example,
var test = {
prop1 : true
};
console.log(test.prop1); // true
console.log(test["prop1"]); // also true
Read more here : https://developer.mozilla.org/en/JavaScript/Guide/Working_with_Objects

Categories