Home > OS >  how to get res in custom data with nestjs or express
how to get res in custom data with nestjs or express

Time:02-24

Middleware replied that it was sent to the controller after checking the authentication.

>> middleware code
async use(req: any, res: any, next: () => void) {
    const validate = await this.validate(req.cookies.token);
    const permission = validate;
    res.permission = permission;
    req.permission = permission;
    next();
}




>> controller code
root(@Res() res: Response, @Req() req: Request) {
    if (res.permission) {
        res.redirect("some where");
    } else {
        return res.render('some views')
    }
    
}

error message is 'Property 'permission' does not exist on type 'Response<any, Record<string,any>>' But the controller can't use this.How do you use it?

I'm sorry I'm not good at English.

CodePudding user response:

A quick fix for this would be to defined your custom type and extend Request.

Something like this

type MyResType = {
  permission: boolean;
};

root(@Res() res: Response & MyResType) {
  if (res.permission) {
    return res.redirect("admin");
  }
  
  return res.render('404')
}

It would not complain about the type however this is not recommended way of doing things in Nestjs. You should not use @Res, @Res decorators unless it's really necessary.

I suggest using guards alongside filters instead and here is the helpful explaination.

At least this is the proper way of doing it and testing will be easier.

  • Related