nestjs context.swithToHttp (). getRequest () возвращает неопределенное - PullRequest
0 голосов
/ 22 октября 2019

Я хочу создать RolesGuard для Graphql

Я создаю Roles Decorator, как следующий

export const Roles = (...roles: string[]) => SetMetadata('roles', roles);

И я создаю GqlAuthGuard и RolesGuard как следующий

gql-gurad.ts

@Injectable()
export class GqlAuthGuard extends AuthGuard('jwt') {
    getRequest(context: ExecutionContext){
        const ctx = GqlExecutionContext.create(context);
        return ctx.getContext().req;
    }
}

role-guard.ts

@Injectable()
export class RolesGuard implements CanActivate {
constructor(private readonly reflector: Reflector) {}

    canActivate(context: ExecutionContext): boolean {
        const roles = this.reflector.get<string[]>('roles', context.getHandler());
        if (!roles) {
            return true;
        }
        const request = context.switchToHttp().getRequest();
        const user = request.user;

        ...
    }
}

, но строкаconst request = context.switchToHttp().getRequest(); возвращает неопределенное значение.

и я использую двух охранников, таких как:

@AuthGuard(GqlAuthGuard, RolesGuard)
@Mutation(...)

Что я пропустил ??

1 Ответ

0 голосов
/ 22 октября 2019

Я решил это сам.

const request = context.switchToHttp().getRequest();
const user = request.user;

to

const ctx = GqlExecutionContext.create(context);
const user = ctx.getContext().req.user;

Я нашел это по каналу разногласий nestjs.

https://discordapp.com/channels/520622812742811698/520649487924985885

...