Skip to content

middleware

John Biundo edited this page Aug 25, 2019 · 2 revisions

Middleware Chapter

With this chapter, if you want to follow along, check out the middleware-start branch and go to the following along section.

If you just want a final version of the project as of the end of the chapter, check out the middleware-end branch, and proceed to the upon completion section.

Following along

Before adding any code

To follow a standard folder structure, I recommend you create a top level folder under src called common. This convention allows you to collect up non-module-specific code that is used across the app. Within common, we will create a middleware folder, and later, other folders to contain other types of "common" code. Our folder structure will now look like this:

nest-cats
└───src
    └───cats
    │   └───dto
    │   └───interfaces
    └───common
        └───middleware

Refer to the comments below, corresponding to chapter sections, to guide you through the code changes for nest cats as you proceed through the docs chapter.

Middleware section

Start by adding the class-based middleware. Create src/common/middleware/logger.middleware.ts as shown in the docs, here.

The docs go on to describe a number of ways matching middleware to routes. Read through these, and when you get to the Middleware consumer section, return here.

Middleware consumer

Next, apply middleware for our GET cats route by updating src/app.module.ts using the example in the docs, here. Be sure to leave our AppController and AppService intact in this file. When done, it should look like this:

import { Module, NestModule, MiddlewareConsumer } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { CatsModule } from './cats/cats.module';
import { LoggerMiddleware } from './common/middleware/logger.middleware';
import { CatsController } from './cats/cats.controller';

@Module({
  imports: [CatsModule],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule implements NestModule {
  configure(consumer: MiddlewareConsumer) {
    consumer.apply(LoggerMiddleware).forRoutes(CatsController);
  }
}

Upon completion

You now have middleware defined for the CatsController routes. You can either proceed using your code or, as always, if you've run into any issues, you can checkout the middleware-end branch to get caught up with the code as of the end of this chapter.

You should now be able to test the app with some REST requests, and observe our LoggingMiddleware in action in the console output.

HTTPie routes for testing middleware

Create a cat

http POST :3000/cats name=Fred age:=3 breed='Alley Cat'

Get cats

http GET :3000/cats

What's next

Next up is the Exception filters chapter.

Clone this wiki locally