当前位置:网站首页>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
边栏推荐
- Dry goods collection | Vulkan game engine video tutorial
- win10电脑系统里的视频不显示缩略图
- Uva1592 Database
- [FreeRTOS interrupt experiment]
- Basic knowledge and examples of binary tree
- 程序员在互联网行业的地位 | 每日趣闻
- 麥斯克電子IPO被終止:曾擬募資8億 河南資產是股東
- Selection of slow motion function
- CADD course learning (7) -- Simulation of target and small molecule interaction (flexible docking autodock)
- The IPO of mesk Electronics was terminated: Henan assets, which was once intended to raise 800 million yuan, was a shareholder
猜你喜欢
MPLS experiment
[Zhao Yuqiang] deploy kubernetes cluster with binary package
图论的扩展
English Vocabulary - life scene memory method
CADD course learning (8) -- virtual screening of Compound Library
Distributed transaction solution
满足多元需求:捷码打造3大一站式开发套餐,助力高效开发
Redis —— Redis In Action —— Redis 实战—— 实战篇一 —— 基于 Redis 的短信登录功能 —— Redis + Token 的共享 session 应用— 有代码
IPv6 comprehensive experiment
11. Intranet penetration and automatic refresh
随机推荐
Bubble sort
树莓派3.5寸屏幕白屏显示连接
Sqlserver query results are not displayed in tabular form. How to modify them
Ue5 small knowledge points to enable the setting of lumen
Postman测试报告
几种RS485隔离通讯的方案介绍
Visio draw fan
Word cover underline
11. Intranet penetration and automatic refresh
newton interpolation
Programmers' position in the Internet industry | daily anecdotes
acwing周赛58
Excellent PM must experience these three levels of transformation!
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
Vulnerability discovery - vulnerability probe type utilization and repair of web applications
Request (request object) and response (response object)
I'd like to ask about the current MySQL CDC design. In the full volume phase, if a chunk's binlog backfill phase,
饼干(考试版)
Selection of slow motion function
【HBZ分享】云数据库如何定位慢查询