Inheritance in Node.JS - node.js

I am using node.js and programming based on express.js. I have tried to use util.inherits to implement inheritance in JavaScript. What I've tried is as follows:
//request.js
function Request() {
this.target = 'old';
console.log('Request Target: ' + this.target);
}
Request.prototype.target = undefined;
Request.prototype.process = function(callback) {
if (this.target === 'new')
return true;
return false;
}
module.exports = Request;
//create.js
function Create() {
Create.super_.call(this);
this.target = 'new';
}
util.inherits(Create, Request);
Create.prototype.process = function(callback) {
if (Create.super_.prototype.process.call(this, callback)) {
return callback({ message: "Target is 'new'" });
} else {
return callback({ message: "Target is not 'new'" });
}
}
module.exports = Create;
//main.js
var create = new (require('./create'))();
create.process(function(msg) {
console.log(msg);
});
My scenario is :
I have Request as base class and Create as child class. Request has field target that initialize old in Request constructor.
Now, I create Create class object which first call Request constructor and then initialize target field with new. When I call process function of Create, I expect to get message of target is 'new' but it returns another!
I searched similar threads for this, but all are what i tried! Can any one explain what was wrong?
Thanks in advance :)

util.inherits has really awkward super_... anyway, this should work:
Create.super_.prototype.process.call(this, callback);
But really,
var super_ = Request.prototype;
And then the syntax becomes almost convenient:
super_.process.call(this, callback);

Related

NodeJS: call func from inside another func in same file

I have NodeJS program.
In one class, I have various utility methods. One function, safeGithubPush, calls safeString, another func in the same class
module.exports = {
safeString(stringToCheck) {
console.log(validator.isAscii(stringToCheck), validator.matches(stringToCheck, /^((\w)*[-.]?(\w)*)*$/))
return (
validator.isAscii(stringToCheck) &&
validator.matches(stringToCheck, /^((\w)*[-.]?(\w)*)*$/)
);
},
safeGithubPush(currentJob) {
if (
!currentJob ||
!currentJob.payload ||
!currentJob.payload.repoName ||
!currentJob.payload.repoOwner ||
!currentJob.payload.branchName
) {
this.logIn(
currentJob,
`${' (sanitize)'.padEnd(15)}failed due to insufficient job definition`
);
throw invalidJobDef;
}
if (
this.safeString(currentJob.payload.repoName) &&
this.safeString(currentJob.payload.repoOwner) &&
this.safeString(currentJob.payload.branchName)
) {
return true;
}
throw invalidJobDef;
},
}
While this.logIn(), another func in the utility class, works just fine, I get the error for safeString:
Error caught by first catch: TypeError: this.safeString is not a function
I followed a solution offer by another SO post:
safeString: function(stringToCheck){
...
}
safeGithubPush(currentJob) {
...
if (
this.safeString(currentJob.payload.repoName) &&
this.safeString(currentJob.payload.repoOwner) &&
this.safeString(currentJob.payload.branchName)
) {
return true;
}
}
But this also gets a, TypeError: this.safeString is not a function.
I'm not using arrow functions, which is the explanation for this error on a different SO post
I don't think the reason is determinable with the code you are currently presenting. It likely has something to do with how you are calling safeGithubPush. If you do something that would change the this binding the this.safeString is going to fail.
const foo = {
fizz() {
console.log("fizz");
},
buzz() {
this.fizz();
}
};
// "this" is correct
foo.buzz();
// "this" has no fizz to call
const myFizz = foo.buzz;
myFizz();
Considering you are attaching these to module.exports I am going to guess that you pull these functions off in a require call and then try to use them bare which makes the problem obvious after looking at my example above:
// Ignore these 2 lines, they let this look like node
const module = {};
const require = () => module.exports;
// Ignore above 2 lines, they let this look like node
// Your module "some.js"
module.exports = {
safeString(str) {
return true;
},
safeGithubPush(currentJob) {
if (!this.safeString("some")) {
throw new Error("Not safe");
}
return true;
}
};
try {
// Some consumer module that doesn't work
const {safeGithubPush} = require("./some.js");
const isItSafe = safeGithubPush();
console.log(`Safe? ${isItSafe}`);
} catch (err) {
console.error("Didn't bind right \"this\"");
}
try {
// Some consumer module that DOES work
const someModule = require("./some.js");
const isItSafe = someModule.safeGithubPush();
console.log(`Safe? ${isItSafe}`);
} catch (err) {
console.error(err);
}
I would restructure this code. You say these are utility functions which makes me think you don't really want to have to structure them with this in mind.
Instead of attaching them all to module.exports at their definition, define them outside and directly reference the functions you want to use, then attach them to exports so other modules can use the functions:
function safeString(stringToCheck) {
return true;
}
function safeGithubPush(currentJob) {
if (!safeString("some")) {
throw new Error("Not safe");
}
return true;
}
module.exports = {
safeString,
safeGithubPush
};

passing function to a class in nodejs

I have a function that I need to pass to a class I have defined in nodeJs.
The use case scenario is I want to give the implementer of the class the control of what to do with the data received from createCall function. I don't mind if the method becomes a member function of the class. Any help would be appreciated.
//Function to pass. Defined by the person using the class in their project.
var someFunction = function(data){
console.log(data)
}
//And I have a class i.e. the library.
class A {
constructor(user, handler) {
this.user = user;
this.notificationHandler = handler;
}
createCall(){
var result = new Promise (function(resolve,reject) {
resolve(callApi());
});
//doesn't work. Keeps saying notificationHandler is not a function
result.then(function(resp) {
this.notificationHandler(resp);
}) ;
//I want to pass this resp back to the function I had passed in the
// constructor.
//How do I achieve this.
}
callApi(){ ...somecode... }
}
// The user creates an object of the class like this
var obj = new A("abc#gmail.com", someFunction);
obj.createCall(); // This call should execute the logic inside someFunction after the resp is received.
Arrow functions (if your Node version supports them) are convenient here:
class A {
constructor(user, handler) {
this.user = user;
this.notificationHandler = handler;
}
createCall() {
var result = new Promise(resolve => {
// we're fine here, `this` is the current A instance
resolve(this.callApi());
});
result.then(resp => {
this.notificationHandler(resp);
});
}
callApi() {
// Some code here...
}
}
Inside arrow functions, this refers to the context that defined such functions, in our case the current instance of A. The old school way (ECMA 5) would be:
createCall() {
// save current instance in a variable for further use
// inside callback functions
var self = this;
var result = new Promise(function(resolve) {
// here `this` is completely irrelevant;
// we need to use `self`
resolve(self.callApi());
});
result.then(function(resp) {
self.notificationHandler(resp);
});
}
Check here for details: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions#No_separate_this

Making an asynchronous function synchronous for the Node.js REPL

I have a library that connects to a remote API:
class Client(access_token) {
void put(key, value, callback);
void get(key, callback);
}
I want to set up a Node.js REPL to make it easy to try things out:
var repl = require('repl');
var r = repl.start('> ');
r.context.client = new Client(...);
The problem is that an asynchronous API is not convenient for a REPL. I'd prefer a synchronous one that yields the result via the return value and signals an error with an exception. Something like:
class ReplClient(access_token) {
void put(key, value); // throws NetworkError
string get(key); // throws NetworkError
}
Is there a way to implement ReplClient using Client? I'd prefer to avoid any dependencies other than the standard Node.js packages.
You can synchronously wait for stuff with the magic of wait-for-stuff.
Based on your example specification:
const wait = require('wait-for-stuff')
class ReplClient {
constructor(access_token) {
this.client = new Client(access_token)
}
put(key, value) {
return checkErr(wait.for.promise(this.client.put(key, value)))
}
get(key) {
return checkErr(wait.for.promise(this.client.get(key)))
}
}
const checkErr = (maybeErr) => {
if (maybeErr instanceof Error) {
throw maybeErr
} else {
return maybeErr
}
}

NodeJs giving me a Object #<Object> has no method

I have a class along with its helper class defined:
function ClassA(){
this.results_array = [];
this.counter = 0;
this.requestCB = function(err, response, body){
if(err){
console.log(err);
}
else{
this.counter++;
var helper = new ClassAHelper(body);
this.results_array.concat(helper.parse());
}
};
};
function ClassAHelper(body){
this._body = body;
this.result_partial_array = [];
this.parse = function(){
var temp = this.parseInfo();
this.result_partial_array.push(temp);
return this.result_partial_array;
};
this.parseInfo = function(){
var info;
//Get some info from this._body
return info
};
};
NodeJS gives me the following error:
TypeError: Object #<Object> has no method 'parseInfo'
I cannot figure out why I can't call this.parseInfo() from inside ClassAHelper's parse method.
If anyone can explain a possible solution. Or at least, what is the problem? I tried reordering the function declarations, and some other ideas, but to no avail.
P.S. I tried simplifying the code for stackoverflow. Hepefully it still makes sense :)
P.P.S This is my first stackoverflow question. Hopefully I did everything right. :)
Here's a simplified example which works:
function A() {
this.x = function (){
return this.y();
};
this.y = function (){
return "Returned from y()";
};
}
var a = new A();
a.x();
Notice the use of new and calling the method with a.x().
How are you creating an instance of your functions and calling parse in ClassAHelper?
Is it anything like these:
var a = A();
a.x();
// Or
A.x()
this is scoped to the function it is inside. So, when you do this.parse=function(){, there is a new this. To keep ClassAHelper's this, you have to pass it in or reference it inside the anonymous function you made. The following example assigns this to a variable outside of the function and references it inside the function:
function ClassAHelper(body){
this._body = body;
this.result_partial_array = [];
var self = this;
this.parse = function(){
var temp = self.parseInfo();
self.result_partial_array.push(temp);
return self.result_partial_array;
};
this.parseInfo = function(){
var info;
//Get some info from this._body
return info;
};
};
Further reading and other ways of doing it:
Why do you need to invoke an anonymous function on the same line?

How to test one function of a class and how to avoid some code when test a function?

Sample code:
function TestClass() {
var this.name = 'test';
var this.host = '...';
var this.port = '...';
//...
this.connection = this.createConnection(....);
}
TestClass.prototype.testFunc = function(data) {
if(data == this.name) {
return true;
} else {
return false;
}
}
Testclass.prototype.createConnection = function (...) {
//some code
//a real HTTP connection will be created
//some code
}
Now I want to test testFunc, it has a class variable this.name, so I have to create a TestClass instance. But if I create TestClass instance, a real HTTP connection will be created. How can I avoid this real HTTP connection when testing?
In situation like this, how can I write the test code?
Try to simply re-define createConnection in your test, before you instantiate TestClass.
TestClass.prototype.createConnection = function() {
console.log("Called redefined createConnection");
}
You should mock the dependency that make the request not your class you wanna test. Take a look at this nock, a HTTP mocking and expectations library

Resources