Unable to access "this" inside controllers
Closed this issue · 5 comments
I have a simple controller with the following code
import expressAsyncHandler from 'express-async-handler'
import { Controller, ClassErrorMiddleware, Post, Wrapper } from '@overnightjs/core'
import { Logger } from '@overnightjs/logger'
import { OK } from 'http-status-codes'
import { myAsyncAction } from './actions'
import { LogErrorAndStop } from '../middleware/error-handlers'
@Controller("api/auth")
@ClassErrorMiddleware(LogErrorAndStop)
export class AuthController {
private thingINeedFromClass: string
constructor() {
this.thingINeedFromClass = "TEST"
}
@Post("sign-up")
@Wrapper(expressAsyncHandler)
private async signUp(req: Request, res: Response): Promise<void> {
Logger.Info("Sign up called")
Logger.Info(req.body, true)
console.log(this) // <----
await myAsyncAction(this.thingINeedFromClass)
res.status(OK)
}
}
When I log this
it's undefined
. If I try and call the same function in this class without the Class decorator, this
is accessible as expected.
overnight version 1.7.2
Thanks !
This was resolved by checking out an older state of my app, then checking master back out 🤔
I have this issue too with 1.7.2. Checking out older states dont solve this.
I'll stay in 1.6.15.
Hey @joeykilpatrick Sorry to keep calling you but this is due to another change in your pull request and I think it's helpful to point it out.
This change right here on line 156:
let callBack: (...args: any[]) => any = controller[member];
is what was causing 'this' to be undefined. I reverted it back to:
let callBack = (req: Request, res: Response, next: NextFunction) => {
return controller[member](req, res, next);
};
Please test all methods in the Sample Project before doing pull-requests. Everyone version 1.7.3 should fix this issue.
Sorry @seanpmaxwell for this one, but reverting reopens #42, and causes tests to fail. Note that the actual method (callback
) does not have to be of that type and can have an unlimited number of arguments of any type if a wrapper is used. The following change will fix the issue.
let callBack: (...args: any[]) => any = (...args: any[]): any => {
return controller[member](...args);
};
I'm sorry that my pull request had these side effects. Without tests for the sample project, it is difficult to know what will break when additional code is written. This is a great library, but not having any tests makes it impossible to contribute without issues like this.
I can submit a pull request for the code above and an additional test for this behavior, but if you would rather I not make any more changes, please let me know. I really like this library and use it for some personal projects, but if you do not want any further contributions from me, then I will understand.
@joeykilpatrick v1.7.4 has this change