#How to create response middleware?

8 messages · Page 1 of 1 (latest)

zinc pier
#

I remember that middlewares often follow the onion layer behavior that we can execute codes after the handler function completed it will traverse back the layer. But, I this code is not following that behavior. How do I make sure that the part after next() is running after the handler (controller) function complete?

@Injectable()
export class TransactionMiddleware implements NestMiddleware {
  constructor(private dbService: DBAuth) {}

  async use(req: Request, res: Response, next: NextFunction) {
    await this.dbService.db.transaction(async (tx) => {
      this.dbService.tx = tx;

      // TODO: how to not let this block finishes before the `next()` function completed.
      next();
      console.log('this runs before code inside next function');
    });
  }
}
spring turret
#

That's not how middleware works in express

#

You probably want to use an event handler for res.on('finish', handler)

zinc pier
spring turret
#

I'm not sure I understand what you're wanting to do

zinc pier
#

Basically I want to run some handler inside a database transaction context, the repositories are request-scoped, so with every request the dbService.tx will either null or not.
The project I got already a little bit complicated, so writing that transaction in every handler will be tedious.

spring turret
#

You might be able to make use of an Interceptor instead as they have a pre and post controller portion

zinc pier