Pintac
Pintac

Reputation: 1585

Typescript express middleware

I have a simple auth middleware for express. It checks header and if all cool it calls next()

Now when i am in "DoSomething" "this" is equal to global and not the instance of "Test" and "this.DoSomeThingPrivate" is undefined.

I have tried the

DoSomeThingPrivate :() => void;

this.DoSomeThingPrivate = () => {
...
}

pattern. But also does not work.

import express = require('express');

var app = express();

class Test {    
    constructor() {        
    }

    DoSomething(req:express.Request, res:express.Response, next:Function) :void {       
        this.DoSomeThingPrivate();
    }

    private DoSomeThingPrivate() :void
    {       
    }
}

var test = new Test();

app.use(test.DoSomething);

Relates to this

Any Ideas...

thanks

Upvotes: 9

Views: 45565

Answers (2)

basarat
basarat

Reputation: 276269

The following should work fine i.e. use fat arrow for DoSomething not DoSomethingPrivate:

import * as express from 'express';

var app = express();

class Test {    
    constructor() {        
    }

    // important: 
    DoSomething = (req:express.Request, res:express.Response, next:express.NextFunction) => {       
        this.DoSomeThingPrivate();
    }

    private DoSomeThingPrivate() :void
    {       
    }
}

var test = new Test();

app.use(test.DoSomething);

Note: You should not need to use bind. Also https://www.youtube.com/watch?v=KDrWLMUY0R0&hd=1

Upvotes: 21

johngeorgewright
johngeorgewright

Reputation: 1005

You've passed a reference just to the function itself. The function's instance will be global. You need to bind the function to the instance of test.

app.use(test.DoSomething.bind(test));

Upvotes: 10

Related Questions