How to pass data to next middleware function in NodeJS - node.js

I'm writing my own implementation of middleware for a socket system. I've read through the source code of Laravel's middleware and some documentation on ExpressJS's implementation for inspiration.
However, I'm getting stuck on passing the data from one middleware handler to another.
I wrote a very basic example below. The output should be 4 but I don't know how to pass the output from one handler to the other. I'm guessing by setting a temporary variable, but I'm not sure how performant that is.
let each = require('lodash/each')
class Middleware {
constructor() {
this.handlers = [
function (data) {return data + 1},
function (data) {return data + 2}
]
}
}
class Router {
constructor() {
this.middleware = new Middleware
}
route(data) {
each(this.middleware.handlers, function(handler) {
handler(data) // no idea what to do here
})
}
}
class Socket {
constructor() {
this.router = new Router
}
write(data) {
return this.router.route(data)
}
}
let router = new Router
console.log(socket.write(1)) // should be 4

Change the route function inside Router class as following and the result of socket.write(1) will be 4:
class Router {
constructor() {
this.middleware = new Middleware
}
route(data) {
each(this.middleware.handlers, function (handler) {
data = handler(data)
})
return data
}
}

Related

Dependecy Injection using Class into Express

I'm using Express into a TypeScript project and I have the following situation
This is my route file
...
import findAllUsersFactory from "src/factory/FindAllUsers";
routes.get("/users", findAllUsersFactory().handle);
...
This is the factory where I do a sequence of injections
const findAllUsersFactory = () => {
const findAllUserRepository = new PrismaUsersRepository();
const findAllUsersBusiness = new FindAllUsersBusiness(findAllUserRepository);
const findAllUsersController = new FindAllUsersController(findAllUsersBusiness);
return findAllUsersController;
};
This is my Controller
class FindAllUsersController {
constructor(private findUserBusiness: FindAllUsersBusiness) { }
async handle(request: Request, response: Response) {
const allUsers = await this.findUserBusiness.execute();
return response.status(200).send({ allUsers });
}
}
And finally my Business
class FindAllUsersBusiness {
constructor(private usersRepository: IUsersRepository) {}
async execute() {
return this.usersRepository.findAll();
}
}
The problem is that I'm getting an error "Cannot read property 'execute' of undefined" because the findUserBusiness into handle function is undefined. And what I can't understand is that if I change my route to
routes.get("/users", (request, response) => {
findAllUsersFactory().handle(request, response);
});
it works
I've tried to log the functions, but I can say why findUserBusiness is undefined since it came from the constructor, and since the handle functions came from an instance of FindAllUsersController it should have it "defined"
You need to make some adjustments in order to adapt your factory to the way router.get expects its parameters.
const findAllUsersFactory = (req, res) => {
const findAllUserRepository = new PrismaUsersRepository();
const findAllUsersBusiness = new FindAllUsersBusiness(findAllUserRepository);
const findAllUsersController = new FindAllUsersController(findAllUsersBusiness);
return findAllUsersController.handle(req, res)
};
Then in your router you need to do the following:
routes.get("/users", findAllUsersFactory);

Why can't I access `userService` variable after express instance running in Nodejs

I was trying to create an endpoint in node.js, more specifically in express
but I am not sure why I can't access userService variable when requesting from a client.
I've gotten Cannot read property 'userService' of undefined, but when i move ServicesFactory.getInstance().getUserService() inside the signUp function it works?!
I am guessing that node.js garbage collects it due to it's not being used until the user make a request.
export class UserApi implements WebEndpoint {
router: Router
userService = ServicesFactory.getInstance().getUserService()
constructor() {
this.router = Router()
this.router.post('/signup', this.signUp)
}
signUp(req: Request, res: Response): void {
const user: User = req.body
this.userService.signUp(user)
res.send("Successfully registered")
}
}
I found the problem, so basically I am a noob.
consider this example
class a {
constructor() {
this.a1 = 'hello';
}
greet(){
const greeting = `${this.a1} dude!`;
console.log(greeting);
};
}
class b {
b1 = new a();
constructor() {
this.b1.greet.call();
}
}
new b();
Now it wouldn't run, because b class called greet method with a new context, the same with express when you provide a function as a handler on an Express endpoint it will be called with a new set of context (read:this) that's why this.userService in my code above won't work because there is no userService property in the context provided by Express.
The solution is simple. Arrow function.
signUp = (req: Request, res: Response): void => {
const user: User = req.body
this.userService.signUp(user)
res.send("Successfully registered")
}
Now the function will inherit it's class's context.You can refer to this for more detail answer.

Puppeteer mock page request object

import { Page } from 'puppeteer/lib/Page';
export class MonitorRequestHelper {
public static monitorRequests(page: Page, on = false) {
if(on) {
page.on('request', req => {
if (['image', 'font', 'stylesheet'].includes(req.resourceType())) {
// Abort requests for images, fonts & stylesheets to increase page load speed.
req.abort();
} else {
req.continue();
}
});
} else {
return true;
}
}
}
I am trying to mock and spy the function to check if it got called at least once.
Also, it would be helpful if some explain me how to mock and spy event-emitter object.
The source code is available on https://github.com/Mukesh23singh/puppeteer-unit-testing
If you want to test that your logic in monitorRequests works, you need to pass in a fake Page object with an event emitter interface that produces a fake request that you can test on.
Something like:
import {spy} from 'sinon';
// Arrange
const fakePage = { on(type, cb) { this[type] = cb; } }; // "event emitter"
const fakeRequest = {
abort: sinon.spy(),
resourceType() { return 'image'; }
};
monitorRequests( fakePage, true );
// Act
// trigger fake request
fakePage['request'](fakeRequest);
// Assert
assert(fakeRequest.abort.called);

Pass 'this' to a class variable inside constructor

I am interested, how to pass this to a class variable inside a constructor of a parent, so I could use parents methods and access other variables of the parent and call their methods?
Here is my parent class:
var async = require('async');
var Rater = require('./rater')
var Similars = require('./similars')
var Suggestions = require('./suggestions');
module.exports = class Engine {
constructor() {
this.likes = new Rater(this,'likes');
this.dislikes = new Rater(this,'dislikes');
this.similars = new Similars(this);
this.suggestions = new Suggestions(this);
}
And here is the example of usage and where is get the following error:
Cannot read property 'engine' of undefined
at --\\classes\rater.js:89:19
module.exports = class Rater {
constructor(engine,kind) {
this.type = kind;
this.engine = engine;
if(kind == 'likes') //database schemes
this.db = Likes_db;
else if(kind == 'dislikes')
this.db = Dislikes_db;
else if(kind == 'similars')
this.db = Similars_db;
else if(kind == 'suggestions')
this.db = Suggestions_db;
}
//..
//other methods
//..
remove(user,item,done) {
this.db.remove({user: user,item: item},(err) => {
if(err)
return done(err);
async.series([
function(done) {
this.engine.similars.update(user,done); //error-cant enter the method
},
function(done) {
this.engine.suggestions.update(user,done);
}
],function(done) {
});
});
}
}
It has nothing to do with the constructor.
The problem appears because you are using a regular function as the callback and the context switches (you get another this in there).
Use an arrow function instead to keep the same context.
async.series([
(done) => {
this.engine.similars.update(user,done); //error-cant enter the method
},
(done) => {
this.engine.suggestions.update(user,done);
}
],function(done) {
});
Simply doing this works fine:
class Rather {
constructor(engine: Engine) {
engine.method();
}
}
class Engine {
constructor() {
new Rather(this);
}
method() {
console.log('ENgine');
}
}
new Engine();
You can see a working example here.
Note: As an OOP design decision though this is not very clean, you are introducing a cyclic dependency. Try going injection or at least introduce an interface to separate the 2 classes.
Try to define a _this var and then give it to parameter:
module.exports = class Engine {
var _this = this, _constructor = (<any>this).constructor;
constructor() {
this.likes = new Rater(_this,'likes');
this.dislikes = new Rater(_this,'dislikes');
this.similars = new Similars(_this);
this.suggestions = new Suggestions(_this);
}

"this" lost after construct? (ts/node/express)

I am trying to build a simple http app using node-express.
Issue when setting up routes, the constructor of the MyRouter class has this but it's lost in the getRoutes() function.
class Main {
public async run(): Promise<void> {
const myRouter = new MyRouter(this.config);
// this.server is express() during construct
this.server.use("/v1", myRouter.getRoutes);
await this.server.listen(this.config.rest.port);
}
}
class MyRouter {
private router: express.Router;
constructor(private config: any) {
this.router = express.Router();
console.log(this); // Prints the whole Router object!
}
public getRoutes(): express.Router {
console.log(this); // = "undefined" !
this.router.use("/test", otherClass.getRoutes);
return this.router;
}
}
Why is this?
The value of this depends not on where it is defined but by how a function is called. You did this:
this.server.use("/v1", myRouter.getRoutes);
This is equivalent to:
var tmp = myRouter.getRoutes;
this.server.use("/v1", tmp); // `this` will refer to the global object
There are two solutions. Either wrap it in an anonymous function to retain the object that calls the function:
this.server.use("/v1", function(){return myRouter.getRoutes()});
Or use .bind()
this.server.use("/v1", myRouter.getRoutes.bind(myRouter));

Resources