Tsed: Async middleware

Created on 19 Oct 2017  路  9Comments  路  Source: tsedio/tsed

Informations

Type |聽Version
---|---
Question | 2.6.4


Description

I would like to use an async middleware. Is this possible?

Most helpful comment

It's because you use next() function and async at the same time. In your case this example will work:

public $onAuth(req: Request, res: Response, next, options?: any) {
        const firebase: Firebase = InjectorService.get(Firebase);
        const admin = firebase.getAdmin();
        const authorization: string = req.header('Authorization');
        if (!authorization) {
            return next(false);
        }
        const token = authorization.split(' ')[1];
        admin.auth().verifyIdToken(token).then((decodedToken) => {
            console.log(decodedToken);
            next()
        });
}

All 9 comments

Hi @FrozenDroid ,

@Middleware(){
    async user(){}
}

see you :)

Hmm, does that also work with $onAuth? I can't get that to work:

    public async $onAuth(req: Request, res: Response, next, options?: any) {
        const firebase: Firebase = InjectorService.get(Firebase);
        const admin = firebase.getAdmin();
        const authorization: string = req.header('Authorization');
        if (!authorization) {
            return next(false);
        }
        const token = authorization.split(' ')[1];
        await admin.auth().verifyIdToken(token).then((decodedToken) => {
            console.log(decodedToken);
        });
        return next(false);
    }

Before the await, returning next(false); works like it's supposed to. After the await, it ignores the return and behaves as if the user is authenticated.

Can you not mix the conversations? it's disturbing ... ^^

Sorry, I probably misunderstood; I thought $onAuth is essentially a middleware?

I'll continue this thread on the original subject ;) #144

These are two different issues. This one is the problem that it doesn't wait for theawait. The other one is just about finding the best method to inject a factory. The way I do it now, the factory works. I just feel like it could be done better.

It's because you use next() function and async at the same time. In your case this example will work:

public $onAuth(req: Request, res: Response, next, options?: any) {
        const firebase: Firebase = InjectorService.get(Firebase);
        const admin = firebase.getAdmin();
        const authorization: string = req.header('Authorization');
        if (!authorization) {
            return next(false);
        }
        const token = authorization.split(' ')[1];
        admin.auth().verifyIdToken(token).then((decodedToken) => {
            console.log(decodedToken);
            next()
        });
}

That works! Awesome :)
Thanks for such an awesome project!

Thanks ;)

Was this page helpful?
0 / 5 - 0 ratings