初始化nestjs项目
使用pnpm初始化nstjs项目,并生成auth[登录、注册]模块,具体步骤见Nestjs学习笔记 - 掘金 (juejin.cn)
自定义表单验证错误类
创建完dto文件之后,我们需要自定义表单验证错误类
- src/common/validation/validation.pipe.ts
js
// 自定义管道,这样前端入参就会先走管道,然后再出来
import { PipeTransform, Injectable, ArgumentMetadata, HttpStatus, HttpException } from '@nestjs/common'
import { validate } from 'class-validator'
import { plainToInstance } from 'class-transformer'
@Injectable()
export class ValidationPipe implements PipeTransform {
async transform(value: any, metadata: ArgumentMetadata) {
//前台提交的表单数据没有类型,使用 plainToClass 转为有类型的对象用于验证
const object = plainToInstance(metadata.metatype, value)
//根据 DTO 中的装饰器进行验证
const errors = await validate(object)
if (errors.length) {
const messages = errors.map((error) => {
return {
name: error.property,
message: Object.values(error.constraints),
}
})
console.log(messages)
throw new HttpException(messages, HttpStatus.BAD_REQUEST) //nestjs中默认错误状态码是400
}
return value
}
}
然后我们在main.ts中使用即可
js
import { NestFactory } from '@nestjs/core'
import { AppModule } from './app.module'
import { ValidationPipe } from './common/validation/validation.pipe'
import { HttpExceptionFilter } from './common/validation/http-exception.filter'
async function bootstrap() {
const app = await NestFactory.create(AppModule)
app.useGlobalPipes(new ValidationPipe()) //全局管道注入,main.ts没有在模块上,所以依赖注入不能用,因此需要手动new一下
app.useGlobalFilters(new HttpExceptionFilter()) //全局注册过滤器
await app.listen(3000)
}
bootstrap()
初始化prisma
这里具体内容看我上篇文章Nestjs学习笔记 - 掘金 (juejin.cn)
prisma/schema.prisma
js
generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "mysql"
url = env("DATABASE_URL")
}
model user {
id Int @id @default(autoincrement())
name String? @unique
password String
}
model article {
id Int @id @default(autoincrement())
title String @unique
content String @db.Text
}
prisma/seed.ts
js
import { PrismaClient } from '@prisma/client'
import * as bcrypt from 'bcryptjs'
import { Random } from 'mockjs'
const prisma = new PrismaClient()
const run = async () => {
await prisma.user.create({
data: {
name: 'admin',
password: await bcrypt.hashSync('123456'),
},
})
for (let i = 0; i < 50; i++) {
await prisma.atticle.create({
data: {
title: Random.ctitle(1, 30),
content: Random.cparagraph(30, 50),
},
})
}
}
run()
我们利用 npx prisma migrate dev 来生产迁移文件,会自动执行数据填充;我们也可以执行以下命令重置数据库 npx prisma migrate reset
完成注册登录及jwt鉴权
这里具体内容看我上篇文章Nestjs学习笔记 - 掘金 (juejin.cn)
获取文章列表和分页数据
首先创建一个模块 nest g res article --no-spec,选择REST API方案,之后控制器、服务、dto都会被创建出来