当前位置:网站首页>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 httphere 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 cartOr specify path generation $
nest g middleware common/pipe/cart.pipeCreate 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
边栏推荐
- tengine 内核参数
- 麦斯克电子IPO被终止:曾拟募资8亿 河南资产是股东
- [HBZ sharing] how to locate slow queries in cloud database
- Yyds dry goods inventory OSI & tcp/ip
- 二叉树基本知识和例题
- [FreeRTOS interrupt experiment]
- Redis - redis in action - redis actual combat - actual combat Chapter 1 - SMS login function based on redis - redis + token shared session application - with code
- Programmers' position in the Internet industry | daily anecdotes
- Sqlserver query results are not displayed in tabular form. How to modify them
- 内核判断i2c地址上是否挂载外设
猜你喜欢

Patent | subject classification method based on graph convolution neural network fusion of multiple human brain maps

Zynq learning notes (3) - partial reconfiguration

Redis - redis in action - redis actual combat - actual combat Chapter 1 - SMS login function based on redis - redis + token shared session application - with code

麦斯克电子IPO被终止:曾拟募资8亿 河南资产是股东

Guitar Pro 8.0最详细全面的更新内容及全部功能介绍

The most detailed and comprehensive update content and all functions of guitar pro 8.0

Implementation of knowledge consolidation source code 1: epoll implementation of TCP server

Ue5 small knowledge points to enable the setting of lumen

Mysql database storage engine

Crazy God said redis notes
随机推荐
[FreeRTOS interrupt experiment]
Coreldraw2022 new version new function introduction cdr2022
Microservice resource address
The most detailed and comprehensive update content and all functions of guitar pro 8.0
饼干(考试版)
Can Flink SQL read multiple topics at the same time. How to write in with
树莓派3.5寸屏幕白屏显示连接
Sorting out the latest Android interview points in 2022 to help you easily win the offer - attached is the summary of Android intermediate and advanced interview questions in 2022
8. Static file
二叉树基本知识和例题
最高法院,离婚案件判决标准
Digital children < daily question> (Digital DP)
Selection of slow motion function
MPLS experiment
Postman断言
coreldraw2022新版本新功能介绍cdr2022
Crazy God said redis notes
[NOIP2009 普及组] 分数线划定
【LGR-109】洛谷 5 月月赛 II & Windy Round 6
newton interpolation