当前位置:网站首页>Upload nestjs configuration files, configure the use of middleware and pipelines
Upload nestjs configuration files, configure the use of middleware and pipelines
2022-07-06 04:46:00 【Johnny, me】
Nestjs File upload in
- file : https://docs.nestjs.com/techniques/file-upload
Installing a plug-in
- $
yarn add @types/multer
Example
1 ) Simple single upload
The front-end code
<form action="upload/add" method="post" enctype="multipart/form-data"> <input type="file" name="files" /> <br> <br> <input type="submit" value=" Submit "> </form>
Back end code
import { Controller, Get, Render, Post, Body, UseInterceptors, UploadedFile } from '@nestjs/common'; import { FileInterceptor } from '@nestjs/platform-express'; import { createWriteStream } from 'fs'; import { join } from 'path'; @Controller('upload') export class UploadController { @Get() @Render('default/upload') index() { } @Post('add') @UseInterceptors(FileInterceptor('files')) doAdd(@Body() body, @UploadedFile() file) { console.log(body); console.log(file); // Upload picture information Must be in form Configuration in the properties of enctype="multipart/form-data" const writeStream = createWriteStream(join(__dirname, '../../public/upload', `${ Date.now()}-${ file.originalname}`)) writeStream.write(file.buffer); return ' Upload the picture successfully '; } }
2 ) Multiple file upload
- If field equally ( With name All are files), We can choose to use UploadedFiles To deal with , And through for … of To traverse
- If it's not the same , It provides , The following configuration
@Post('upload') @UseInterceptors(FileFieldsInterceptor([ { name: 'avatar', maxCount: 1 }, { name: 'background', maxCount: 1 }, ])) uploadFile(@UploadedFiles() files: { avatar?: Express.Multer.File[], background?: Express.Multer.File[] }) { console.log(files); }
- Or use Any The type of interceptor AnyFilesInterceptor
@Post('upload') @UseInterceptors(AnyFilesInterceptor()) uploadFile(@UploadedFiles() files: Array<Express.Multer.File>) { console.log(files); }
- It should be noted that , Every time we upload , These paths , Image processing , It needs to be encapsulated
Nestjs middleware
- Same as express equally ,nestjs Middleware can also be understood as a pipeline handler between request and response
- It could be a function , It can also be a @Injectable() Decorator decorated class
The role of middleware
- Execute any code
- Make changes to the request and response objects
- End request - Response period
- Call the next middleware function in the stack
- If the current middleware function does not end the request - Response period , It has to call next() Pass control to the next middleware function
- otherwise , The request will be suspended
Creation and use of middleware
1 ) establish
- $
nest g middleware http
here http Is the middleware name - Will generate src/http.middleware.ts file , as follows :
import { Injectable, NestMiddleware } from '@nestjs/common'; @Injectable() export class HttpMiddleware implements NestMiddleware { use(req: any, res: any, next: () => void) { next(); } }
- We follow the document , modified
import { Injectable, NestMiddleware } from '@nestjs/common'; import { Request, Response, NextFunction } from 'express'; @Injectable() export class HttpMiddleware implements NestMiddleware { use(req: Request, res: Response, next: NextFunction) { console.log('Request...'); next(); } }
2 ) stay app.module.ts Use in
import {
Module, NestModule, MiddlewareConsumer } from '@nestjs/common';
import {
HttpMiddleware } from './http.middleware';
import {
CatsModule } from './cats/cats.module'; // modular
@Module({
imports: [CatsModule],
})
export class AppModule implements NestModule {
configure(consumer: MiddlewareConsumer) {
consumer
.apply(HttpMiddleware)
// .forRoutes('cats'); // Indicate which routes can use this middleware
// .forRoutes(someController); // Match all routes // Or pass in the specified controller , But it's not recommended to write
// .forRoutes({path: 'cats', method: RequestMethod.GET}); // Only match GET
// .forRoutes({path: 'cats', method: RequestMethod.ALL}); // Match all methods
// .forRoutes({path: 'cats', method: RequestMethod.ALL}, {path: 'user', method: RequestMethod.ALL}); // Configure multiple
.forRoutes('*'); // Match all routes
}
}
- Of course , We'd better put the middleware into a common module , as follows :./common/middleware/
import { LoggerMiddleware } from './common/middleware/logger.middleware';
- In fact, you can specify the directory when creating $
nest g middleware common/middleware/http.middleware
3 ) An example of configuring multiple middleware
3.1 A configuration
import {
Module, NestModule, MiddlewareConsumer } from '@nestjs/common';
import {
HttpMiddleware } from './http.middleware';
import {
UserMiddleware } from './user.middleware';
@Module({
imports: [],
})
export class AppModule implements NestModule {
configure(consumer: MiddlewareConsumer) {
consumer
.apply(HttpMiddleware).forRoutes('*')
.apply(UserMiddleware).forRoutes('user')
}
}
3.2 Another configuration
// Only the key code is written here
consumer
.apply(NewsMiddleware,UserMiddleware)
.forRoutes({
path: 'u*r', method: RequestMethod.ALL},{
path: 'news', method: RequestMethod.ALL}) // There is no order here
4 ) Functional middleware
// Just write the key code
export function logger(req, res, next) {
console.log(` Functional middleware ...`);
next();
};
export class AppModule implements NestModule {
configure(consumer: MiddlewareConsumer) {
consumer
.apply(HttpMiddleware, logger).forRoutes('*')
}
}
5 ) Global middleware
stay main.ts Use in , Note that you cannot use class middleware , Only functional middleware can be used
// Global middleware can only introduce functional middleware import { logger } from './middleware/logger.middleware'; app.use(logger);
The Conduit
- About pipes :https://docs.nestjs.com/pipes
- The concept of pipeline is mainly used to convert input data into required output data
- Or deal with Get,Post Data submitted
Create pipes
$
nest g pipe cart
Or specify path generation $
nest g middleware common/pipe/cart.pipe
Create a cart The pipe
import { ArgumentMetadata, Injectable, PipeTransform } from '@nestjs/common'; @Injectable() export class CartPipe implements PipeTransform { transform(value: any, metadata: ArgumentMetadata) { return value; } }
explain : The pipe is made up of @Injectable() A class of decorators
Need to achieve PipeTransform This interface , And implement an internal transform Method
Here are two parameters :value,metadata
among , value Is the data transferred to the pipeline , metadata It's a type of
You can modify the incoming value and verify the legitimacy of the incoming value
Use pipes
Use pipes in the controller
import { Controller, Get, Query, UsePipes} from '@nestjs/common'; // Lead in pipe import { CartPipe } from '../../pipe/cart.pipe'; @Controller('cart') export class NewsController { @Get() @UsePipes(new CartPipe()) index(@Query() info){ console.log(info); return 'Cart' } }
You can tell by the code above , First, introduce the pipeline , Then use UsePipes Take the incoming pipeline instance as a parameter as a decorator of the current route
there info Will be introduced into the pipeline , That is, in the pipe value Parameters
after , In the pipeline, you can modify the current value , Verification and other operations
About the calibration in the pipeline
Before receiving data , You need to check the data , At this time, it is more suitable to write relevant programs in the pipeline
generally speaking , We will use the third-party library to help us complete the verification , The official provides us with the use joi Library related examples
https://github.com/hapijs/joi,https://joi.dev/api/?v=17.6.0
Let's do a demonstration
// Used in controller file import { Controller, Get, Query, UsePipes } from '@nestjs/common'; import { UserPipe } from '../../pipe/user.pipe'; import * as Joi from 'joi'; // Definition json schema const userSchema = Joi.object().keys({ name: Joi.string().required(), age: Joi.number().integer().min(6).max(66).required(), }) @Controller('user') export class UserController { @Get() @UsePipes(new UserPipe(userSchema)) index(@Query() info) { console.log(info); return ' User center '; } }
// In the pipeline file import { ArgumentMetadata, Injectable, PipeTransform } from '@nestjs/common'; @Injectable() export class UserPipe implements PipeTransform { private schema; constructor(schema){ this.schema=schema // When instantiating , Parameters of the incoming } transform(value: any, metadata: ArgumentMetadata) { const { error } = this.schema.validate(value); // check // If the error , Prompt , Or uniformly return the same entity data structure , For example, prompt the front end if(error) { return { "success": false}; } return value; } }
The above is the basic usage , Generally speaking, of course , You can also add related message Information , Used to prompt front-end users
More usage , Please refer to the above document
边栏推荐
- 【LGR-109】洛谷 5 月月赛 II & Windy Round 6
- 比尔·盖茨晒18岁个人简历,48年前期望年薪1.2万美元
- ue5 小知识点 开启lumen的设置
- The kernel determines whether peripherals are attached to the I2C address
- 团队协作出了问题,项目经理怎么办?
- 饼干(考试版)
- How do programmers teach their bosses to do things in one sentence? "I'm off duty first. You have to work harder."
- NPM command -- install dependent packages -- Usage / explanation
- 【Try to Hack】john哈希破解工具
- Programmers' position in the Internet industry | daily anecdotes
猜你喜欢
满足多元需求:捷码打造3大一站式开发套餐,助力高效开发
coreldraw2022新版本新功能介绍cdr2022
Coreldraw2022 new version new function introduction cdr2022
The IPO of mesk Electronics was terminated: Henan assets, which was once intended to raise 800 million yuan, was a shareholder
Implementation of knowledge consolidation source code 1: epoll implementation of TCP server
CADD course learning (7) -- Simulation of target and small molecule interaction (flexible docking autodock)
Visio draw fan
How do programmers teach their bosses to do things in one sentence? "I'm off duty first. You have to work harder."
Mysql database storage engine
[mathematical modeling] differential equation -- sustainable development of fishing industry
随机推荐
[NOIP2009 普及组] 分数线划定
RTP gb28181 document testing tool
Selection of slow motion function
Microservice resource address
Luogu deep foundation part 1 Introduction to language Chapter 2 sequential structure programming
The IPO of mesk Electronics was terminated: Henan assets, which was once intended to raise 800 million yuan, was a shareholder
Postman测试报告
ue5 小知识点 开启lumen的设置
Project manager, can you draw prototypes? Does the project manager need to do product design?
满足多元需求:捷码打造3大一站式开发套餐,助力高效开发
ISP learning (2)
[Chongqing Guangdong education] engineering fluid mechanics reference materials of southwestjiaotonguniversity
Word cover underline
Weng Kai C language third week 3.1 punch in
The web project imported the MySQL driver jar package but failed to load it into the driver
After learning classes and objects, I wrote a date class
[Zhao Yuqiang] deploy kubernetes cluster with binary package
Programmers' position in the Internet industry | daily anecdotes
RTP GB28181 文件测试工具
The ECU of 21 Audi q5l 45tfsi brushes is upgraded to master special adjustment, and the horsepower is safely and stably increased to 305 horsepower