lukeautry / tsoa

Build OpenAPI-compliant REST APIs using TypeScript and Node
MIT License
3.33k stars 481 forks source link

Middleware after response #1593

Closed SwagiWagi closed 2 months ago

SwagiWagi commented 4 months ago

Sorting

Expected Behavior

Have the ability to have middlewares of specific routes be called after response has been sent

Current Behavior

Possible Solution

Steps to Reproduce

@Route("user") export class UserController extends Controller { @Middlewares(validateUserId) @Get("{userId}") async getUser(@Path() userId: string) { this.setStatus(200); return {userId: userId}; } }

Now I want a logging middleware to be called (for example), specifically after the response has been sent.

Context (Environment)

Version of the library: 6.1.5 Version of NodeJS: 20.11.0

Detailed Description

Breaking change?

github-actions[bot] commented 4 months ago

Hello there SwagiWagi 👋

Thank you for opening your very first issue in this project.

We will try to get back to you as soon as we can.👀

jackey8616 commented 4 months ago

I assume you are using Express, there is two way to archive such feature.

  1. custom template and make your own handler function, register every route with after middleware by yourself, details you can search on StackOverflow, I believe there is some example such as Call middleware after response sent in Express
  2. tsoa indeed can provides such feature by including an AfterMiddleware decorator. but I doubt the necessity of it right now.

cc @WoH need your opinion.

WoH commented 3 months ago

(req, res, next) => {

  next()

  console.log('post')
}

Should do it, right?

SwagiWagi commented 3 months ago

I believe an AfterMiddleware decorator would be a great feature. It's great for use cases such as:

  1. Tracking the number of completed requests (for billing purposes for example).
  2. Logging.
  3. Disposing resources.

I believe it wouldn't be much work, I can make a PR for this.

jackey8616 commented 3 months ago
(req, res, next) => {

  next()

  console.log('post')
}

Should do it, right?

https://github.com/lukeautry/tsoa/blob/efdb468a5cedcb9bef345f1eed776e8fc621b443/packages/cli/src/routeGeneration/templates/express.hbs#L92-L116

Yes, just call next() in custom template, after L106 would work with after middleware.

github-actions[bot] commented 2 months ago

This issue is stale because it has been open 30 days with no activity. Remove stale label or comment or this will be closed in 5 days

ericwooley commented 2 months ago

Sorry to bring up a dead issue. But this doesn't appear to have been implemented.

I'm happy to do the PR if needed, or maybe there is discussion elsewhere as to why this wasn't added?