#Issue with request scoped service and gateways

9 messages · Page 1 of 1 (latest)

flint veldt
#

I have AuthService which uses CookieService, CookieService Injects REQUEST so it can handle cookie related stuff, and since I'm using passport I can't do that (Didn't quite understand why, but I'm still trying to figure it out), so what I did is follow what the docs said. It worked, but now I can't use the service in websockets.

AuthService

@Injectable({
  scope: Scope.REQUEST,
})
export class AuthService {
  constructor(
    private jwtService: JwtService,
    private userService: UserService,
    private configService: ConfigService,
    private cookieService: CookiesService
  ) {}

  async login(user: User): Promise<Partial<JwtTokens>> {
    "...";
    this.cookieService.set("refresh_token", refresh_token);
    "...";
  }

  async register(credentials: RegisterDTO) {
    try {
      "...";

      return this.login(user);
    } catch (err) {
      "...";
    }
  }
  "...";
}

LocalStrategy


@Injectable()
export class LocalStrategy extends PassportStrategy(Strategy) {
  constructor(private moduleRef: ModuleRef) {
    super({
      passReqToCallback: true,
    });
  }

  async validate(
    request: Request,
    username: string,
    password: string,
  ): Promise<User> {
    const contextId = ContextIdFactory.create();
    this.moduleRef.registerRequestByContextId(request, contextId);
    const authService = await this.moduleRef.resolve(AuthService, contextId);
    const user = await authService.validateUser(username, password);
    if (!user) {
      throw new UnauthorizedException();
    }
    return user;
  }
}

ChatGateway

export class ChatGateway implements OnGatewayConnection {
  constructor(private authService: AuthService) {}

  async handleConnection(client: any, ...args: any[]) {
    try {
      const payload = await this.authService.validateToken(
        client.handshake.query.access_token,
      );
    "..."
    } catch (err) {
      client.disconnect();
    }
  }
}
#

Issue with request scoped service and gateways

old tusk
#

gateways and cron controllers (among others) don't support request scope and it's a real pain making it work

#

I recommend not injecting the request in services, but rather passing it as an argument from controllers or guards explicitly

#

or if you need request context deep inside the app, use AsyncLocalStorage (https://docs.nestjs.com/recipes/async-local-storage) instead of request scoped providers

flint veldt
#

Thank you very much, that is much better than passing it to each request.

#

Do you know why gateways do not support it?

old tusk