This is the 15th day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021
The module
Modules are classes with @Module() decorators. The @Module() decorator provides metadata that Nest uses to organize the application.
The @module() decorator takes an object that describes module properties:
providers | Providers instantiated by the Nest injector and can be shared at least across the module |
---|---|
controllers | A set of controllers that must be created |
imports | A list of imported modules that export the required providers in this module |
exports | Subset of providers that are provided by this module and should be available in other modules. |
The middleware
Middleware is a function called before the routing handler. The middleware functions can access request and response objects, as well as the next() middleware function in the application request response cycle. The next() middleware function is typically represented by a variable named next.
Nest middleware is essentially equivalent to Express middleware. Here are the middleware features described in the official Express documentation:
Middleware functions can perform the following tasks:
- Execute any code.
- Make changes to the request and response objects.
- End the request-response cycle.
- Call the next middleware function in the stack.
- If the current middleware function does not end the request-response cycle, it must call next() to pass control to the next middleware function. Otherwise, the request will be suspended.
import { Injectable, NestMiddleware } from '@nestjs/common';
import { Request, Response, NextFunction } from 'express';
@Injectable()
export class LoggerMiddleware implements NestMiddleware {
use(req: Request, res: Response, next: NextFunction) {
console.log('Request... '); next(); }}Copy the code
Application middleware
Middleware cannot be listed in the @Module() decorator. We must set them up using the module class’s configure() method. Modules containing middleware must implement the NestModule interface. We set LoggerMiddleware on the ApplicationModule layer.
app.module.ts
import { Module, NestModule, MiddlewareConsumer } from '@nestjs/common';
import { LoggerMiddleware } from './common/middleware/logger.middleware';
import { CatsModule } from './cats/cats.module';
@Module({
imports: [CatsModule],
})
export class AppModule implements NestModule {
configure(consumer: MiddlewareConsumer) {
consumer
.apply(LoggerMiddleware)
.forRoutes('cats'); }}Copy the code
You must set forRoutes with an asterisk (*) to match all, or specify the corresponding module
{path: ‘cats’, method: requestMethod. GET} can be configured as an object, only for GET methods
You can also use the wildcard, ‘ab* CD ‘
Functional middleware
export function logger(req, res, next) {
console.log(`Request... `);
next();
};
Copy the code
Multiple middleware
consumer.apply(cors(), helmet(), logger).forRoutes(CatsController);
Copy the code
Global middleware
const app = await NestFactory.create(AppModule);
app.use(logger);
await app.listen(3000);
Copy the code
The pipe
- Transformation: The pipe converts the input data into the desired data output
- Validation: Validates the input data and continues to pass if validation succeeds; An exception is thrown if validation fails;
We use class-Validator and class-Transformer libraries that we need to install manually
Built-in pipe
- ValidationPipe: Validates data using a class-validator validator
For example,
export class CreateCatDto {
@IsString()
@IsNotEmpty()
@Type(() = > String)
readonly name: string;
@IsNumber()
@IsNotEmpty()
@Type(() = > Number)
readonly age: number
@IsString()
@IsNotEmpty()
@Type(() = > String)
readonly breed: string
@Type(() = > Boolean)
readonly isHot: boolean = false
}
Copy the code
use
@Post()
async create(@Body(new ValidationPipe(options)) createCatDto: CreateCatDto) {
this.catsService.create(createCatDto);
return 'Add success 1111'
}
Copy the code
- ParseIntPipe: Converts the parameter to an int
@Get(':id')
async findOne(@Param('id'.new ParseIntPipe()) id) {
return await this.catsService.findOne(id);
}
Copy the code
-
ParseBoolPipe: Convert to Boolean, use the same method as above
-
ParseArrayPipe: Converts to array
-
ParseUUIDPipe: This is used to parse whether a string is a UUID.