Hello there,
I followed the tutorial to create a role guard with reflector injected https://docs.nestjs.com/guards
At runtime, nest throws an exception where we call .get() like so.
const roles = this.reflector.get
[Nest] 5448 - 2018-2-2 13:23:52 [ExceptionsHandler] Cannot read property 'get' of undefined
TypeError: Cannot read property 'get' of undefined at RoleGuard.canActivate (C:\Users\nest\project\src\core\role.guard.ts:11:34) https://docs.nestjs.com/guards
Can you pls check it out?
Dependencies/versions in package.json
"dependencies": {
"@nestjs/common": "^4.5.9",
"@nestjs/core": "^4.5.10",
"@nestjs/microservices": "^4.5.8",
"@nestjs/testing": "^4.5.5",
"@nestjs/websockets": "^4.5.8",
"": "0.0.38",
"body-parser": "^1.18.2",
"express-jwt": "^5.3.0",
"jwks-rsa": "^1.2.1",
"redis": "^2.7.1",
"reflect-metadata": "^0.1.12",
"rxjs": "^5.5.6",
"typescript": "^2.6.2"
}
Hi @ramachandrann,
We need more details, at least more source code. Also, follow official ISSUE_TEMPLATE
I wanted to apply the RoleGuard at bootstrap, but couldn't find any documentation to retrieve an instance of reflector from nest context. That's the real problem. Sorry about the confusion.
//imports left out for brewity
@Guard()
export class RoleGuard implements CanActivate {
constructor(private readonly reflector: Reflector) {}
canActivate(req, context: ExecutionContext): boolean {
//irrelevant code not included.
const roles = this.reflector.get
return true;
}
}
async function bootstrap() {
const app = await NestFactory.create(ApplicationModule);
app.useGlobalGuards(new RoleGuard()); //HOW TO GET a handle to Reflector.
app.use(bodyParser.json());
await app.listen(3000);
}
When you create instance manually, you can create Reflector by yourself:
new RoleGuard(new Reflector());
Thank you so much :)
This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.
Most helpful comment
When you create instance manually, you can create
Reflectorby yourself: