当前位置:网站首页>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
边栏推荐
- Coreldraw2022 new version new function introduction cdr2022
- 树莓派3.5寸屏幕白屏显示连接
- P2022 interesting numbers (binary & digit DP)
- How do programmers teach their bosses to do things in one sentence? "I'm off duty first. You have to work harder."
- Postman管理测试用例
- Recommendation | recommendation of 9 psychotherapy books
- [05-1, 05-02, 05-03] network protocol
- Yyds dry goods inventory OSI & tcp/ip
- DMA use of stm32
- Uva1592 Database
猜你喜欢
L'introduction en bourse de MSK Electronics a pris fin: 800 millions de RMB d'actifs de Henan étaient des actionnaires
Yyds dry inventory automatic lighting system based on CC2530 (ZigBee)
Embedded development program framework
Postman管理测试用例
Crazy God said redis notes
acwing周赛58
Programmers' position in the Internet industry | daily anecdotes
[05-1, 05-02, 05-03] network protocol
Postman关联
Mysql database storage engine
随机推荐
Weng Kai C language third week 3.1 punch in
图论的扩展
Ue5 small knowledge points to enable the setting of lumen
8. Static file
Basic explanation of turtle module - draw curve
acwing周赛58
SQL注入漏洞(MSSQL注入)
也算是学习中的小总结
[NOIP2008 提高组] 笨小猴
Embedded development program framework
Dynamic programming (tree DP)
tengine 内核参数
[Zhao Yuqiang] deploy kubernetes cluster with binary package
Platformio create libopencm3 + FreeRTOS project
Database - MySQL storage engine (deadlock)
Bill Gates posted his 18-year-old resume and expected an annual salary of $12000 48 years ago
C'est un petit résumé de l'étude.
Postman关联
MIT CMS. 300 session 8 – immersion / immersion
cdc 能全量拉去oracle 表嘛