Tuesday 3 May 2016

Proper ES2015 Middleware Class Instantiation?

Finaly trying out ES2015 and I am having a hard time using it in a similar manner to my existing revealing module pattern 'classes'. It seems like best practice is to use the new class syntax for everything but it seems much more restrictive than revealing module pattern classes. My problems right now are in relation to trying to use ES2015 classes as Express middleware. I can only seem to pass arguments to a specific class method which then has an undefined reference to this so it cannot call any other internal class methods. Ideally I want to be able to just call 'app.use(Middleware)' and have the constructor call method1 which uses req, res, next arguments and can call other internal methods like method2 etc. I feel like I am missing something very basic here... ( running Node v5.11 without transpiling )ES2015 Middleware.js:class Middleware { constructor(req, res, next) { console.log(arguments); } method1(req, res, next) { this.method2('test'); } method2(msg) { console.log(msg); } } module.exports = new Middleware(); Revaling Module Pattern Middleware.js:var Middleware = (function(){ var method1 = function(req, res, next) { this.method2('test'); }; var method2 = function(msg) { console.log(msg); }; return { method1: method1 }; })(); module.exports = Middleware; Express:ex 1 let Middleware = require('./Middleware'); app.use(Middleware.method1) // this == undefined, unable to reference any other Class methods ex 2 ( attempting constructor use ) let Middleware = require('./Middleware'); app.use(Middleware) // no req, res, next in constructor

Submitted May 04, 2016 at 05:20AM by qweqweasdqweasdqwe

No comments:

Post a Comment