当前位置:网站首页>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
边栏推荐
- 【HBZ分享】ArrayList的增删慢查询快的原因
- [HBZ share] reasons for slow addition and deletion of ArrayList and fast query
- Supreme Court, judgment standard of divorce cases
- Dry goods collection | Vulkan game engine video tutorial
- What should the project manager do if there is something wrong with team collaboration?
- Knowledge consolidation source code implementation 3: buffer ringbuffer
- 也算是学习中的小总结
- 力扣(LeetCode)186. 翻转字符串里的单词 II(2022.07.05)
- CADD course learning (8) -- virtual screening of Compound Library
- 图论的扩展
猜你喜欢
How to realize automatic playback of H5 video
coreldraw2022新版本新功能介绍cdr2022
English Vocabulary - life scene memory method
The value of two date types is subtracted and converted to seconds
Vulnerability discovery - vulnerability probe type utilization and repair of web applications
Distributed transaction solution
Recommendation | recommendation of 9 psychotherapy books
Introduction of several RS485 isolated communication schemes
MPLS experiment
Fuzzy -- basic application method of AFL
随机推荐
Jd.com 2: how to prevent oversold in the deduction process of commodity inventory?
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
Database - MySQL storage engine (deadlock)
ISP learning (2)
Knowledge consolidation source code implementation 3: buffer ringbuffer
Scala function advanced
Supreme Court, judgment standard of divorce cases
也算是学习中的小总结
Crazy God said redis notes
最高法院,离婚案件判决标准
DMA use of stm32
Request (request object) and response (response object)
Platformio create libopencm3 + FreeRTOS project
tengine 内核参数
Certbot failed to update certificate solution
Can Flink SQL read multiple topics at the same time. How to write in with
Unity screen coordinates ugui coordinates world coordinates conversion between three coordinate systems
Yyds dry goods inventory OSI & tcp/ip
优秀PM必须经历这3层蜕变!
我想问一下 按照现在mysql-cdc的设计,全量阶段,如果某一个chunk的binlog回填阶段,