什么是NestJS
Nest 是一個(gè)漸進(jìn)的 Node.js 框架,可以在 TypeScript 和 JavaScript (ES6、ES7、ES8)之上構(gòu) 建高效、可伸縮的企業(yè)級(jí)服務(wù)器端應(yīng)用程序。
Nest 基于 TypeScript 編寫(xiě)并且結(jié)合了 OOP(面向?qū)ο缶幊蹋?,F(xiàn)P(函數(shù)式編程)和 FRP (函數(shù)式響應(yīng)編程)的相關(guān)理念。在設(shè)計(jì)上的很多靈感來(lái)自于 Angular,Angular 的很多模 式又來(lái)自于 Java 中的 Spring 框架,依賴注入、面向切面編程等,所以我們也可以認(rèn)為: Nest 是 Node.js 版的 Spring 框架。
Nest 框架底層 HTTP 平臺(tái)默認(rèn)是基于 Express 實(shí)現(xiàn)的,所以無(wú)需擔(dān)心第三方庫(kù)的缺失。 Nest 旨在成為一個(gè)與平臺(tái)無(wú)關(guān)的框架。 通過(guò)平臺(tái),可以創(chuàng)建可重用的邏輯部件,開(kāi)發(fā)人員可以利用這些部件來(lái)跨越多種不同類(lèi)型的應(yīng)用程序。 從技術(shù)上講,Nest 可以在創(chuàng)建適配器 后使用任何 Node HTTP 框架。 有兩個(gè)支持開(kāi)箱即用的 HTTP 平臺(tái):express 和 fastify。 您 可以選擇最適合您需求的產(chǎn)品。
NestJs 的核心思想:就是提供了一個(gè)層與層直接的耦合度極小,抽象化極高的一個(gè)架構(gòu) 體系。
官網(wǎng):https://nestjs.com/
中文網(wǎng)站:https://docs.nestjs.cn/
GitHub: https://github.com/nestjs/nest

圖一只是說(shuō)明規(guī)范的模塊方式,實(shí)際上,可以只有根模塊,也可以劃分多個(gè)模塊,互相依賴,只要不是循環(huán)引入就行。
Nestjs 的特性
- 依賴注入容器
- 模塊化封裝
- 可測(cè)試性
- 內(nèi)置支持 TypeScript
- 可基于 Express 或者 fastify
腳手架nest-cli
安裝
npm i -g @nestjs/cli 或者 cnpm i -g @nestjs/cli 或者 yarn global add @nestjs/cli
創(chuàng)建
nest new nestdemo
相關(guān)指令
- nest new 名稱 創(chuàng)建項(xiàng)目
- nest -h/--help 幫助
- nest g co 名稱 創(chuàng)建控制器
- nest g s 名稱 創(chuàng)建服務(wù)
- nest g mi 名稱 創(chuàng)建中間件
- nest g pi 名稱 創(chuàng)建管道
- nest g mo 名稱 創(chuàng)建模塊
- nest g gu 名稱 創(chuàng)建守衛(wèi)
創(chuàng)建類(lèi)型指令都可以指定文件路徑,而且路徑全部是再src目錄下面,例如:
nest g co /aaa/bbb/user 則在src下面就會(huì)存在一個(gè)三級(jí)目錄,user的目錄下
有一個(gè)以u(píng)ser命名大寫(xiě)的控制器 UserController.ts文件
注意:凡是以腳手架創(chuàng)建的模塊,控制器等等都會(huì)自動(dòng)添加到對(duì)應(yīng)配置位置,不需要手動(dòng)配置
控制器
Nest 中的控制器層負(fù)責(zé)處理傳入的請(qǐng)求, 并返回對(duì)客戶端的響應(yīng)。
import { Controller, Get } from '@nestjs/common';
@Controller('article')
export class ArticleController {
@Get()
index(): string {
return '這是 article 里面的 index';
}
@Get('add')
add(): string {
return '這是 article 里面的 index';
}
}
關(guān)于 nest 的 return: 當(dāng)請(qǐng)求處理程序返回 JavaScript 對(duì)象或數(shù)組時(shí),它將自動(dòng)序列化為 JSON。但是,當(dāng)它返回一個(gè)字符串時(shí),Nest 將只發(fā)送一個(gè)字符串而不是序列化它。這使響應(yīng)處理變得簡(jiǎn)單:只需要返回值,Nest 負(fù)責(zé)其余部分。
Get Post通過(guò)方法參數(shù)裝飾器獲取傳值
- 基本栗子
nestjs 內(nèi)置裝飾器的時(shí)候必須得在@nestjs/common 模塊下面引入對(duì)應(yīng)的裝飾器
import { Controller, Get, Post } from '@nestjs/common';
@Controller('cats')
export class CatsController {
@Post()
create(): string {
return 'This action adds a new cat';
}
@Get()
findAll(): string {
return 'This action returns all cats';
}
}
Nestjs 也提供了其他 HTTP 請(qǐng)求方法的裝飾器 @Put() 、@Delete()、@Patch()、 @Options()、 @Head()和 @All()
- Nest中獲取請(qǐng)求參數(shù)
在 Nestjs 中獲取 Get 傳值或者 Post 提交的數(shù)據(jù)的話我們可以使用 Nestjs 中的裝飾器來(lái)獲取
@Request() req
@Response() res
@Next() next
@Session() req.session
@Param(key?: string) req.params / req.params[key]
@Body(key?: string) req.body / req.body[key]
@Query(key?: string) req.query / req.query[key]
@Headers(name?: string) req.headers / req.headers[name]
import { Controller, Get, Post,Query,Body } from '@nestjs/common';
@Controller('news')
export class NewsController {
@Get()
getAbout(@Query() query): string {
console.log(query);
//這里獲取的就是所有的 Get 傳值
return '這是 about'
}
//針對(duì)參數(shù)是 localhost:3000/news/list?id=zq&age=12
@Get('list')
getNews(@Query('id') id):string {
console.log(id);
//這里獲取的就是 Get 傳值里面的 Id 的值
//如果@Query()則是整個(gè)id=zq&age=12的對(duì)象
return '這是新聞'
}
@Post('doAdd')
async addNews(@Body() newsData){
console.log(newsData);
return '增加新聞’'
}
}
- 動(dòng)態(tài)路由
// 針對(duì)的參數(shù)是 /name/id這種類(lèi)型,例如/name/1
@Get(':id')
findOne(@Param() params): string {
console.log(params.id);
return `This action returns a #${params.id} cat`;
}
補(bǔ)充: @Param() 裝飾器訪問(wèn)以這種方式聲明的路由參數(shù),該裝飾器應(yīng)添 加到函數(shù)簽名中。@Param可以用在get或者post,但是都是針對(duì) localhost:3000/news/list?id=zq&age=12這種才可以獲取,而針對(duì)body內(nèi)部都是獲取不到的,可以使用@Body
- 綜合案例
@Controller('news')
export class NewsController {
//依賴注入
constructor(private readonly newsService:NewsService){}
@Get('pip')
@UsePipes(new NewsPipe(useSchema))
indexPip(@Query() info){
// console.log(info);
return info;
}
@Get()
@Render('default/news')
index(){
return {
newsList:this.newsService.findAll()
}
}
/**
* 路由順序:如果此時(shí)訪問(wèn)http://localhost:3000/news/add
* 則會(huì)正確執(zhí)行,如果把a(bǔ)dd移動(dòng)到:id下面,則只會(huì)執(zhí)行:id的
*/
@Get('add')
addData(@Query('id') id){
return id+'------';
}
//同理,這個(gè)模糊匹配如果移動(dòng)到:id下面,訪問(wèn)http://localhost:3000/news/aaa
//也會(huì)只匹配:id的路由
@Get('a*a')
indexA(){
return '模糊匹配';
}
//動(dòng)態(tài)路由 /add/1
@Get(':id')
indexB(@Param('id') id){
return id;
}
}
Swagger集成
中文文檔地址:https://docs.nestjs.cn/6/recipes?id=openapi-swagger
- 安裝
npm install --save @nestjs/swagger swagger-ui-express
如果你正在使用fastify,你必須安裝 fastify-swagger 而不是 swagger-ui-express
npm install --save @nestjs/swagger fastify-swagger
- 引導(dǎo)
- main.ts
- 引入:import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
- 編碼
import { NestFactory } from '@nestjs/core'; import { AppModule } from './app.module'; import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger'; async function bootstrap() { const app = await NestFactory.create(AppModule); const options = new DocumentBuilder() .setTitle('Cats example') .setDescription('The cats API description') .setVersion('1.0') //下面兩者結(jié)合組成請(qǐng)求基本路徑 .setHost('http://www.baidu.com') .setBasePath('/api') // .addTag('cats') 分類(lèi) .build(); const document = SwaggerModule.createDocument(app, options); //指定文檔路徑 SwaggerModule.setup('api-docs', app, document); await app.listen(3000); } bootstrap(); - 打開(kāi)http://localhost:3000/api-docs/#/,如下圖二
圖二.png
swagger基本使用
- 創(chuàng)建Dto
import { ApiModelProperty } from '@nestjs/swagger';
export class CreatePostDto{
@ApiModelProperty({description:"應(yīng)用名稱",example:'示例值'})
title:string
@ApiModelProperty({description:"應(yīng)用內(nèi)容"})
content:string
}
- @ApiModelProperty() 裝飾器接受選項(xiàng)對(duì)象
export const ApiModelProperty: (metadata?: {
description?: string;
required?: boolean; //代表是否必須存在該參數(shù)
type?: any;
isArray?: boolean;
collectionFormat?: string;
default?: any;
enum?: SwaggerEnumType;
format?: string;
multipleOf?: number;
maximum?: number;
exclusiveMaximum?: number;
minimum?: number;
exclusiveMinimum?: number;
maxLength?: number;
minLength?: number;
pattern?: string;
maxItems?: number;
minItems?: number;
uniqueItems?: boolean;
maxProperties?: number;
minProperties?: number;
readOnly?: boolean;
xml?: any;
example?: any;
}) => PropertyDecorator;
- 完整例子
只是入門(mén),更多例子是使用規(guī)則查看文檔
import { Controller, Get, Post, Body, Query, Param } from '@nestjs/common';
import { AppService } from './app.service';
import { ApiUseTags, ApiOperation, ApiModelProperty } from '@nestjs/swagger';
class CreatePostDto{
//默認(rèn)required都是true,Model上面會(huì)有個(gè)紅色星號(hào),代表必須填寫(xiě),
//但是實(shí)際上swagger本身不會(huì)限制,只是告知作用,swagger本身請(qǐng)求正常
@ApiModelProperty({description:"應(yīng)用名稱",example:'示例值',maxLength:1,required:false})
title:string
@ApiModelProperty({description:"應(yīng)用內(nèi)容"})
content:string
}
@Controller('app')
@ApiUseTags('默認(rèn)標(biāo)簽')//其實(shí)是大分類(lèi)
export class AppController {
constructor(private readonly appService: AppService) {}
@Get('hello')
@ApiOperation({title:"顯示hello"}) //api的title描述/注釋
getHello(@Query() query,@Param() params): any[] {
return this.appService.getHello();
}
@Post('create')
@ApiOperation({title:"創(chuàng)建應(yīng)用"})
createApp(@Body() body:CreatePostDto): CreatePostDto{
return body;
}
@Get(':id')
@ApiOperation({title:'應(yīng)用詳情'})
detail(@Param('id') id:number){
return{
id
}
}
}
總結(jié):swagger本身注解只是告知作用,不同于graphql,例如required本身是沒(méi)什么作用只是告知使用者需要填寫(xiě),但是實(shí)際上需要與否還是程序控制;同理,不論填寫(xiě)不填寫(xiě)swagger都會(huì)進(jìn)行請(qǐng)求,最終結(jié)果以邏輯控制為準(zhǔn)。
參數(shù)驗(yàn)證
- 安裝
npm i class-validator class-transformer --save
- 啟用全局管道
- main.ts中
app.useGlobalPipes(new ValidationPipe())
- 導(dǎo)包
- 在需要使用參數(shù)校驗(yàn)的文件內(nèi)導(dǎo)入
import { IsNotEmpty } from 'class-validator'
class CreatePostDto{
@ApiModelProperty({description:"應(yīng)用名稱",example:'示例值'})
//**此處就是**
@IsNotEmpty({message:'我是沒(méi)填寫(xiě)title屬性的時(shí)候,返回的給前端的錯(cuò)誤信息'})
title:string
@ApiModelProperty({description:"應(yīng)用內(nèi)容"})
content:string
}
說(shuō)明: Nest 自帶兩個(gè)開(kāi)箱即用的管道,即 ==ValidationPipe== 和 ==ParseIntPipe==
補(bǔ)充:ParseIntPipe簡(jiǎn)單使用
可把id自動(dòng)轉(zhuǎn)換成Int類(lèi)型
@Get(':id')
async findOne(@Param('id', new ParseIntPipe()) id) {
return await this.catsService.findOne(id);
}
總結(jié): 內(nèi)置管道都支持全局,方法,參數(shù)三種級(jí)別的使用
文檔連接
靜態(tài)資源
官方文檔:https://docs.nestjs.com/techniques/mvc
app.useStaticAssets('public');
- 栗子
async function bootstrap() {
//指定平臺(tái)
const app = await NestFactory.create<NestExpressApplication>(AppModule);
//配置靜態(tài)資源
//app.useStaticAssets(join(__dirname,'..','public'))
//上面是直接訪問(wèn)http://localhost:3000/a.png
//下面可以設(shè)置虛擬目錄http://localhost:3000/public/a.png
// app.useStaticAssets(join(__dirname,'..','public'),{
// prefix:'/public/'
// })
//如下方式也可以,因?yàn)槟J(rèn)nest會(huì)去尋找根目錄下面的參數(shù)一文件夾
app.useStaticAssets('public',{
prefix:'/public/'
})
await app.listen(3000);
}
注意:NestFactory.create<NestExpressApplication>(AppModule);指定了范型其實(shí)就是Nest的平臺(tái),默認(rèn)使用的是express的平臺(tái),因?yàn)殪o態(tài)資源涉及平臺(tái)的選擇所以必須指定了。
模板引擎
官方文檔:https://docs.nestjs.com/techniques/mvc
- 安裝
cnpm i ejs --save
- 配置
app.setBaseViewsDir(join(__dirname, '..', 'views')) // 放視圖的文件
app.setViewEngine('ejs');
- 完整代碼
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
//靜態(tài)資源中間件依賴于具體平臺(tái),所以可以先引入express
import { NestExpressApplication } from '@nestjs/platform-express';
// import { join } from 'path';
//此時(shí)下面如果使用path則就是path.join
// import * as path from 'path';
async function bootstrap() {
const app = await NestFactory.create<NestExpressApplication>(AppModule);
app.useStaticAssets('public',{
prefix:'/public/'
})
//配置模板引擎,需要先安裝模板引擎
// app.setBaseViewsDir(join(__dirname,'..','views'))
app.setBaseViewsDir('views');
app.setViewEngine('ejs');
await app.listen(3000);
}
bootstrap();
==注意此處引入path的方式==
- 渲染頁(yè)面
@Controller('user')
export class UserController {
@Get()
@Render('default/user')
index(){
//注意一般有render的路由則return值都是給模板引擎使用的
//所以nest會(huì)判斷,一般都是對(duì)象,返回字符串會(huì)報(bào)錯(cuò)
// return '用戶中心';
//此處是字符串key還是直接命名都可以被ejs搜索到
// return {"name":"zs",age:12}
}
}
說(shuō)明:default指的是views下面的default文件夾內(nèi)部的user模板
重定向
import { Controller, Get, Post, Body,Response, Render} from '@nestjs/common';
@Controller('user')
export class UserController {
@Get()
@Render('default/user')
index(){
return {"name":"張三"};
}
@Post('doAdd')
doAdd(@Body() body,@Response() res){
console.log(body);
res.redirect('/user'); //路由跳轉(zhuǎn)
}
}
提供者
幾乎所有的東西都可以被認(rèn)為是提供者 - service, repository, factory, helper 等等。他們都可以通過(guò) constructor注入依賴關(guān)系,也就是說(shuō),他們可以創(chuàng)建各種關(guān)系。但事實(shí)上,提供者不過(guò)是一個(gè)用@Injectable() 裝飾器注解的類(lèi)。
export interface Cat {
name: string;
age: number;
breed: string;
}
import { Controller, Get, Post, Body } from '@nestjs/common';
import { CreateCatDto } from './dto/create-cat.dto';
import { CatsService } from './cats.service';
@Controller('cats')
export class CatsController {
//依賴注入
constructor(private readonly catsService: CatsService) {}
@Post()
async create(@Body() createCatDto: CreateCatDto) {
this.catsService.create(createCatDto);
}
@Get()
async findAll(): Promise<Cat[]> {
return this.catsService.findAll();
}
}
cookie
- 安裝
cnpm instlal cookie-parser --save
- 在 main.ts 中引入 cookie-parser
import * as cookieParser from 'cookie-parser'
- 在 main.ts 配置中間件
app.use(cookieParser());
- 設(shè)置 cookie
res.cookie("name",'zhangsan',{maxAge: 900000, httpOnly: true});
- 獲取 Cookies
@Get('getCookies')
getCookies(@Request() req){
return req.cookies.name;
}
cookie參數(shù)說(shuō)明
| 屬性 | 說(shuō)明 |
|---|---|
| domain | 域名 |
| expires | 過(guò) 期 時(shí) 間 ( 秒 ) , 在 設(shè) 置 的 某 個(gè) 時(shí) 間 點(diǎn) 后 該 Cookie 就 會(huì) 失 效 , 如 expires=Wednesday, 09-Nov-99 23:12:40 GMT |
| maxAge | 最大失效時(shí)間(毫秒),設(shè)置在多少后失效 |
| secure | 當(dāng) secure 值為 true 時(shí),cookie 在 HTTP 中是無(wú)效,在 HTTPS 中才有效 |
| path | 表示 cookie 影響到的路,如 path=/。如果路徑不能匹配時(shí),瀏覽器則不發(fā)送這 個(gè) Cookie |
| httpOnly | 是微軟對(duì) COOKIE 做的擴(kuò)展。如果在 COOKIE 中設(shè)置了“httpOnly”屬性,則通 過(guò)程序(JS 腳本、applet 等)將無(wú)法讀取到 COOKIE 信息,防止 XSS 攻擊產(chǎn)生 |
| signed | 表 示 是 否 簽 名 cookie, 設(shè) 為 true 會(huì) 對(duì) 這 個(gè) cookie 簽 名 , 這 樣 就 需 要 用 res.signedCookies 而不是 res.cookies 訪問(wèn)它。被篡改的簽名 cookie 會(huì)被服務(wù)器拒絕,并且 cookie 值會(huì)重置為它的原始值,說(shuō)白了==加密== |
相關(guān)代碼
- 設(shè)置 cookie
res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true })
res.cookie('name', 'tobi', { domain: '.example.com', path: '/admin', secure: true });
res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true });
- 獲取cookie
req.cookies.name
- 刪除 cookie
res.cookie('rememberme', '', { expires: new Date(0)});
res.cookie('username','zhangsan',{domain:'.ccc.com',maxAge:0,httpOnly:true});
加密cookie
- 配置中間件的時(shí)候需要傳參
app.use(cookieParser('123456'));
- 設(shè)置 cookie 的時(shí)候配置 signed 屬性
res.cookie('userinfo','hahaha',{domain:'.ccc.com',maxAge:900000,httpOnly:true,signed:true});
- signedCookies 調(diào)用設(shè)置的 cookie
console.log(req.signedCookies);
說(shuō)明:加密的cookie使用3這種方式獲取
session
- 安裝
cnpm install express-session --save
- 導(dǎo)入
import * as session from 'express-session';
- 設(shè)置中間價(jià)
app.use(session({ secret: 'keyboard cat', cookie: { maxAge: 60000 }}))
- 使用
設(shè)置值 req.session.username = "張三";
獲取值 req.session.username
- 常用參數(shù)
app.use(session({
secret: '12345',
name: 'name',
cookie: {maxAge: 60000},
resave: false,
saveUninitialized: true
}));
- 參數(shù)說(shuō)明
| 屬性 | 說(shuō)明 |
|---|---|
| secret | 一個(gè) String 類(lèi)型的字符串,作為服務(wù)器端生成 session 的簽名 |
| name | 返回客戶端的 key 的名稱,默認(rèn)為 connect.sid,也可以自己設(shè)置 |
| resave | 強(qiáng)制保存 session 即使它并沒(méi)有變化,。默認(rèn)為 true。建議設(shè)置成 |
| saveUninitialized | 強(qiáng)制將未初始化的 session 存儲(chǔ)。當(dāng)新建了一個(gè) session 且未設(shè)定屬性或值時(shí),它就處于 未初始化狀態(tài)。在設(shè)定一個(gè) cookie 前,這對(duì)于登陸驗(yàn)證,減輕服務(wù)端存儲(chǔ)壓力,權(quán)限控制是有幫助的。(默 認(rèn):true)。建議手動(dòng)添加。 |
| cookie | 設(shè)置返回到前端 key 的屬性,默認(rèn)值為{ path: ‘/’, httpOnly: true, secure: false, maxAge: null }。 |
| rolling | 在每次請(qǐng)求時(shí)強(qiáng)行設(shè)置 cookie,這將重置 cookie 過(guò)期時(shí)間(默認(rèn):false) |
- 常用方法
req.session.destroy(function(err) { /*銷(xiāo)毀 session*/ })
req.session.username='張三'; //設(shè)置
session req.session.username //獲取
session req.session.cookie.maxAge=0; //重新設(shè)置 cookie 的過(guò)期時(shí)間
上傳
官方文檔:https://docs.nestjs.com/techniques/file-upload
單文件上傳
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 {
@Post('doAdd')
@UseInterceptors(FileInterceptor('pic')) //pic對(duì)應(yīng) <input type="file" name="pic" id="">
doAdd(@Body() body,@UploadedFile() file){
// console.log(body);
// console.log(file);
let cws=createWriteStream(join(__dirname,'../../public/upload/',`${Date.now()}---${file.originalname}`))
cws.write(file.buffer);
return '上傳圖片成功';
}
}
<form action="upload/doAdd" method="post" enctype="multipart/form-data">
<input type="text" name="title" placeholder="新聞標(biāo)題">
<br>
<br>
<input type="file" name="pic" id="">
<br>
<input type="submit" value="提交">
</form>
說(shuō)明:注意enctype="multipart/form-data"屬性必須添加
多文件上傳
import { Controller, UseInterceptors, Get, Post, Render, Body, UploadedFiles } from '@nestjs/common';
import { createWriteStream } from 'fs';
import { FilesInterceptor } from '@nestjs/platform-express';
import { join } from 'path';
@Controller('uploadmany')
export class UploadmanyController {
@Post('doAdd')
//注意此處是FileFieldsInterceptor代表多文件的name不同的攔截器
// @UseInterceptors(FileFieldsInterceptor([
// { name: 'pic1', maxCount: 1 },
// { name: 'pic2', maxCount: 1 }
// ]))
//注意此處是FilesInterceptor而上面是FileFieldsInterceptor
@UseInterceptors(FilesInterceptor('pic')) //多個(gè)文件name屬性相同的情況下
doAdd(@Body() body, @UploadedFiles() files) {
for (const file of files) {
let cws = createWriteStream(join(__dirname, '../../public/upload/', `${Date.now()}---${file.originalname}`))
cws.write(file.buffer);
}
return '上傳多個(gè)文件成功';
}
}
注意:此處html中的name相同和不同使用的處理方式不同
<!-- 注意此處上傳文件的enctype -->
<form action="uploadmany/doAdd" method="post" enctype="multipart/form-data">
<input type="text" name="title" placeholder="新聞標(biāo)題">
<br>
<br>
<input type="file" name="pic" id="">
<input type="file" name="pic" id="">
<br>
<input type="submit" value="提交">
</form>
中間價(jià)
中間件就是匹配路由之前或者匹配路由完成做的一系列的操作。中間件中如果想往下 匹配的話,需要寫(xiě) next()
中間件任務(wù)
- 執(zhí)行任何代碼。
- 對(duì)請(qǐng)求和響應(yīng)對(duì)象進(jìn)行更改。
- 結(jié)束請(qǐng)求-響應(yīng)周期。
- 調(diào)用堆棧中的下一個(gè)中間件函數(shù)。
- 如果當(dāng)前的中間件函數(shù)沒(méi)有結(jié)束請(qǐng)求-響應(yīng)周期, 它必須調(diào)用 next() 將控制傳遞給下一個(gè)中間 件函數(shù)。否則, 請(qǐng)求將被掛起。
Nest 中間件可以是一個(gè)函數(shù),也可以是一個(gè)帶有@Injectable()裝飾器的類(lèi)
使用中間件
- 創(chuàng)建
nest g middleware init
import { Injectable, NestMiddleware } from '@nestjs/common';
@Injectable()
export class InitMiddleware implements NestMiddleware {
use(req: any, res: any, next: () => void) {
console.log(Date());
next();
}
}
- 配置中間件
在 app.module.ts 中繼承 NestModule 然后配置中間件
export class AppModule implements NestModule{
configure(consumer:MiddlewareConsumer) {
/**
* 中間件相關(guān)
*/
//寫(xiě)*表示匹配所有路由
// consumer.apply(InitMiddleware).forRoutes('*');
//匹配指定路由
// consumer.apply(InitMiddleware).forRoutes('news');
//直接傳入控制器:不推薦
// consumer.apply(InitMiddleware).forRoutes(NewsController);
// consumer.apply(InitMiddleware).forRoutes({path:'ab*cd',method:RequestMethod.ALL});
//所有路由都匹配InitMiddleware但是UserMiddleware不光匹配InitMiddleware
//還匹配UserMiddleware
// consumer.apply(InitMiddleware,logger).forRoutes('*')
// .apply(UserMiddleware).forRoutes('user')
//都可以添加多個(gè):代表user/news都可以匹配InitMiddleware,UserMiddleware
// consumer.apply(InitMiddleware,UserMiddleware).
// forRoutes({path:'user',method:RequestMethod.ALL},{path:'news',method:RequestMethod.ALL})
}
}
- 多個(gè)中間件
consumer.apply(cors(), helmet(), logger).forRoutes(CatsController);
- 函數(shù)式中間件
export function logger(req, res, next) {
console.log(`Request...`);
next();
};
- 全局中間件
//全局中間件只能引入函數(shù)式中間件,引入類(lèi)中間件會(huì)報(bào)錯(cuò)
import { logger} from './middleware/logger.middleware'
const app = await NestFactory.create(ApplicationModule);
app.use(logger);
await app.listen(3000);
全局中間件只能使用函數(shù)式中間件
管道
Nestjs 中的管道可以將輸入數(shù)據(jù)轉(zhuǎn)換為所需的輸出。此外,它也可以處理驗(yàn)證, 當(dāng)數(shù)據(jù)不正確時(shí)可能會(huì)拋出異常。
- 創(chuàng)建
nest g pipe news
import { ArgumentMetadata, Injectable, PipeTransform, BadRequestException, HttpStatus } from '@nestjs/common';
import * as Joi from '@hapi/joi';
@Injectable()
export class NewsPipe implements PipeTransform {
// constructor(private readonly schema:Joi.Schema){
// }
constructor(private readonly schema:Joi.Schema){}
transform(value: any, metadata: ArgumentMetadata) {
// console.log(value); //value一般都是get/post等請(qǐng)求傳遞過(guò)來(lái)的值
// value.age=30; 如果這樣修改之后,控制器里面的數(shù)據(jù)就變了
const {error}=this.schema.validate(value);
if (error) {
// throw new BadRequestException('Validate failed')
return error;
}
return value;
}
}
- 使用
import { Controller,Get, Param, Query, Render, UsePipes } from '@nestjs/common';
import { NewsService } from './news.service';
import { NewsPipe } from '../pipe/news.pipe';
import * as Joi from '@hapi/joi';
let useSchema:Joi.Schema=Joi.object().keys({
name:Joi.string().required(),
age:Joi.number().integer().min(6).max(66).required()
});
@Controller('news')
export class NewsController {
//依賴注入
constructor(private readonly newsService:NewsService){}
@Get('pip')
@UsePipes(new NewsPipe(useSchema))
indexPip(@Query() info){
// console.log(info);
return info;
}
@Get()
@Render('default/news')
index(){
return {
newsList:this.newsService.findAll()
}
}
/**
* 路由順序:如果此時(shí)訪問(wèn)http://localhost:3000/news/add
* 則會(huì)正確執(zhí)行,如果把a(bǔ)dd移動(dòng)到:id下面,則只會(huì)執(zhí)行:id的
*/
@Get('add')
addData(@Query('id') id){
return id+'------';
}
//同理,這個(gè)模糊匹配如果移動(dòng)到:id下面,訪問(wèn)http://localhost:3000/news/aaa
//也會(huì)只匹配:id的路由
@Get('a*a')
indexA(){
return '模糊匹配';
}
//動(dòng)態(tài)路由 /add/1
@Get(':id')
indexB(@Param('id') id){
return id;
}
}
安裝joi: cnpm i @hapi/joi --save
模塊
模塊是具有 @Module() 裝飾器的類(lèi)。 @Module() 裝飾器提供了元數(shù)據(jù),Nest 用它來(lái)組織應(yīng)用 程序結(jié)構(gòu)。

每個(gè) Nest 應(yīng)用程序至少有一個(gè)模塊,即根模塊。根模塊是 Nest 開(kāi)始安排應(yīng)用程序樹(shù)的地方。事實(shí)上,根模塊可能是應(yīng)用程序中唯一的模塊,特別是當(dāng)應(yīng)用程序很小時(shí),但是對(duì)于大型程序來(lái)說(shuō)這是沒(méi)有意義的。在大多數(shù)情況下,您將擁有多個(gè)模塊,每個(gè)模塊都有一組緊密 相關(guān)的功能。
@module() 裝飾器接受一個(gè)描述模塊屬性的對(duì)象
| 屬性 | 描述 |
|---|---|
| providers | 由 Nest 注入器實(shí)例化的提供者,并且可以至少在整個(gè)模塊中共享 |
| controllers | 必須創(chuàng)建的一組控制器 |
| imports | 導(dǎo)入模塊的列表,這些模塊導(dǎo)出了此模塊中 所需提供者,注意導(dǎo)入的是模塊 |
| exports | 由本模塊提供并應(yīng)在其他模塊中可用的提供 者的子集 |
模塊共享
- 共享模塊:只是一個(gè)普通模塊
import { Module } from '@nestjs/common';
import { BaseService } from './service/base/base.service';
@Module({
providers: [BaseService],
exports:[BaseService]
})
export class ShareModule {}
總結(jié):其實(shí)就是module內(nèi)部exports的東西,此時(shí)是一個(gè)基礎(chǔ)服務(wù)類(lèi)(可以是很多),只要導(dǎo)出了,其他模塊只要導(dǎo)入了該模塊,則該模塊的所有exports的都可以通過(guò)依賴注入方式直接使用,而不需要一個(gè)個(gè)導(dǎo)入service或者provider,然后放到想使用的模塊的provider中。
- 使用共享模塊
import { Module } from '@nestjs/common';
import { UserController } from './controller/user/user.controller';
import { NewsService } from './service/news/news.service';
import { ShareModule } from '../share/share.module';
@Module({
imports:[ShareModule],
controllers: [UserController],
providers: [NewsService],
})
export class AdminModule {
}
此時(shí)新板塊導(dǎo)入了module,沒(méi)有導(dǎo)入具體外部service例如上面的BaseService,但是可以依賴注入在現(xiàn)在的模塊中直接使用。
- 使用共享模塊導(dǎo)出的service
import { Controller, Get } from '@nestjs/common';
import {BaseService} from '../../../share/service/base/base.service'
@Controller('admin/user')
export class UserController {
constructor(private readonly baseService:BaseService){}
@Get()
index(){
console.log(this.baseService.getData());
return "哈哈"
}
}
==模塊總結(jié):==由上面可知,其實(shí)所有模塊都可以導(dǎo)入,只要不出現(xiàn)循環(huán)導(dǎo)入就都可以,而模塊的概念,加強(qiáng)了約束,即使import導(dǎo)入了對(duì)應(yīng)service,只要沒(méi)有在對(duì)應(yīng)module導(dǎo)入module,則運(yùn)行就報(bào)錯(cuò)。
守衛(wèi)
文檔: https://docs.nestjs.com/pipes
守衛(wèi)是一個(gè)使用 @Injectable() 裝飾器的類(lèi)。守衛(wèi)應(yīng)該實(shí)現(xiàn) CanActivate 接口。
守衛(wèi)有一個(gè)單獨(dú)的責(zé)任。它們確定請(qǐng)求是否應(yīng)該由路由處理程序處理。到目前為止,訪問(wèn)限 制邏輯大多在中間件內(nèi)。這樣很好,因?yàn)橹T如 token 驗(yàn)證或?qū)?request 對(duì)象附加屬性與 特定路由沒(méi)有強(qiáng)關(guān)聯(lián)。但中間件是非常笨的。它不知道調(diào)用 next() 函數(shù)后會(huì)執(zhí)行哪個(gè)處 理程序。另一方面,守衛(wèi)可以訪問(wèn) ExecutionContext 對(duì)象,所以我們確切知道將要執(zhí)行 什么。
==簡(jiǎn)單說(shuō):==
在 Nextjs 中如果我們想做權(quán)限判斷的話可以在守衛(wèi)中完成,也可以在中間件中完成,但是一般通過(guò)守衛(wèi)最好。
- 創(chuàng)建
nest g gu auth
import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
import { Observable } from 'rxjs';
@Injectable()
export class AuthGuard implements CanActivate {
canActivate(
context: ExecutionContext,
): boolean | Promise<boolean> | Observable<boolean> {
// let n=Math.random();
// if (n>0.3) {
// return false;
// }
//守衛(wèi)返回false則無(wú)法訪問(wèn)路由,true可以
//判斷cookie或者session
//其實(shí)context.switchToHttp().getRequest();就相當(dāng)于express的req,所以什么path屬性等等都有
// const {cookies,session}=context.switchToHttp().getRequest();
// console.log(cookies,session);
return true;
}
}
- 使用守衛(wèi)
@Get('guard')
@UseGuards(AuthGuard)
guard(@Query() info){
console.log(info);
return `this is guard`;
}
### 也可以直接加在控制器上面
@Controller('cats')
@UseGuards(RolesGuard)
export class CatsController {}
### 全局使用守衛(wèi)
app.useGlobalGuards(new AuthGuard());
- 模塊上使用守衛(wèi)
import {Module} from '@nestjs/common';
import {APP_GUARD} from '@nestjs/core';
@Module({
providers:[
{
provide:APP_GUARD,
useClass:RolesGuard
}
]
})
export class AppModule{}
攔截器
-
作用
- 在函數(shù)執(zhí)行之前/之后綁定額外的邏輯
- 轉(zhuǎn)換從函數(shù)返回的結(jié)果
- 轉(zhuǎn)換從函數(shù)拋出的異常
- 擴(kuò)展基本函數(shù)行為
- 根據(jù)所選條件完全重寫(xiě)函數(shù) (例如, 緩存目的)
創(chuàng)建
import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common';
import { Observable } from 'rxjs';
import { tap } from 'rxjs/operators';
@Injectable()
export class LoggingInterceptor implements NestInterceptor {
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
console.log('Before...');
const now = Date.now();
return next
.handle()
.pipe(
tap(() => console.log(`After... ${Date.now() - now}ms`)),
);
}
}
由于 handle() 返回一個(gè)RxJS Observable,我們有很多種操作符可以用來(lái)操作流。在上面的例子中,我們使用了 tap() 運(yùn)算符,該運(yùn)算符在可觀察序列的正常或異常終止時(shí)調(diào)用函數(shù)。
- 使用
@UseInterceptors(LoggingInterceptor)
export class CatsController {}
此處使用LoggingInterceptor,初始化控制反轉(zhuǎn)交給框架本身,雖然可以傳入new的實(shí)例,但是不建議
- 全局綁定
const app = await NestFactory.create(ApplicationModule);
app.useGlobalInterceptors(new LoggingInterceptor());
- 模塊綁定
import { Module } from '@nestjs/common';
import { APP_INTERCEPTOR } from '@nestjs/core';
@Module({
providers: [
{
provide: APP_INTERCEPTOR,
useClass: LoggingInterceptor,
},
],
})
export class ApplicationModule {}
執(zhí)行順序
過(guò)濾器詳情其實(shí)就是異常過(guò)濾器,整個(gè)流程不見(jiàn)得一定會(huì)指定,但是出現(xiàn)異常時(shí)候會(huì)進(jìn)入,詳情查看官方文檔
graph LR
客戶端請(qǐng)求-->中間件
中間件-->守衛(wèi)
守衛(wèi) -->攔截器之前
攔截器之前 -->管道
管道--> 控制器處理并響應(yīng)
控制器處理并響應(yīng) -->攔截器之后
攔截器之后 -->過(guò)濾器
- 接收客戶端發(fā)起請(qǐng)求
- 中間件去做請(qǐng)求處理,比如helmet,csrf,rate limiting,compression等等常用的處理請(qǐng)求的中間件。
- 守衛(wèi)就驗(yàn)證該用戶的身份,如果沒(méi)有權(quán)限或者沒(méi)有登錄,就直接拋出異常,最適合做權(quán)限管理。
- 攔截器根據(jù)作者解釋?zhuān)瑪r截器之前不能修改請(qǐng)求信息。只能獲取請(qǐng)求信息。
- 管道做請(qǐng)求的數(shù)據(jù)驗(yàn)證和轉(zhuǎn)化,如果驗(yàn)證失敗拋出異常。
- 這里處理響應(yīng)請(qǐng)求的業(yè)務(wù),俗稱controller,處理請(qǐng)求和服務(wù)橋梁,直接響應(yīng)服務(wù)處理結(jié)果。
- 攔截器之后只能修改響應(yīng)body數(shù)據(jù)。
- 最后走過(guò)濾器:如果前面任何位置發(fā)生拋出異常操作,都會(huì)直接走它。
總結(jié)
模塊是按業(yè)務(wù)邏輯劃分基本單元,包含控制器和服務(wù)。控制器是處理請(qǐng)求和響應(yīng)數(shù)據(jù)的部件,服務(wù)處理實(shí)際業(yè)務(wù)邏輯的部件。
中間件是路由處理Handler前的數(shù)據(jù)處理層,只能在模塊或者全局注冊(cè),可以做日志處理中間件、用戶認(rèn)證中間件等處理,中間件和express的中間件一樣,所以可以訪問(wèn)整個(gè)request、response的上下文,模塊作用域可以依賴注入服務(wù)。全局注冊(cè)只能是一個(gè)純函數(shù)或者一個(gè)高階函數(shù)。
管道是數(shù)據(jù)流處理,在中間件后路由處理前做數(shù)據(jù)處理,可以控制器中的類(lèi)、方法、方法參數(shù)、全局注冊(cè)使用,只能是一個(gè)純函數(shù)??梢宰鰯?shù)據(jù)驗(yàn)證,數(shù)據(jù)轉(zhuǎn)換等數(shù)據(jù)處理。
守衛(wèi)是決定請(qǐng)求是否可以到達(dá)對(duì)應(yīng)的路由處理器,能夠知道當(dāng)前路由的執(zhí)行上下文,可以控制器中的類(lèi)、方法、全局注冊(cè)使用,可以做角色守衛(wèi)。
攔截器是進(jìn)入控制器之前和之后處理相關(guān)邏輯,能夠知道當(dāng)前路由的執(zhí)行上下文,可以控制器中的類(lèi)、方法、全局注冊(cè)使用,可以做日志、事務(wù)處理、異常處理、響應(yīng)數(shù)據(jù)格式等。
過(guò)濾器是捕獲錯(cuò)誤信息,返回響應(yīng)給客戶端??梢钥刂破髦械念?lèi)、方法、全局注冊(cè)使用,可以做自定義響應(yīng)異常格式。
中間件、過(guò)濾器、管道、守衛(wèi)、攔截器,這是幾個(gè)比較容易混淆的東西。他們有個(gè)共同點(diǎn)都是和控制器掛鉤的中間抽象處理層,但是他們的職責(zé)卻不一樣。
NestJS很多提供的內(nèi)部功能,看似功能重復(fù),但是實(shí)際上有明確的職責(zé)劃分,按照約定來(lái),能使結(jié)構(gòu)清晰,代碼更好維護(hù)
