You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

2.7 KiB

生命周期

客户端 中间件 守卫 拦截器 管道 控制器 服务 拦截器 过滤器 响应 客户端

  • 中间件
    • 全局中间件
    • 模块中间件
  • 守卫
    • 全局守卫
    • 控制器守卫
    • 路由守卫
  • 拦截器
    • 全局拦截器pre/post
    • 控制器拦截器pre/post
    • 路由拦截器pre/post
  • 管道
    • 全局管道
    • 控制器管道
    • 路由管道
    • 路由参数管道
  • 过滤器
    • 路由过滤器
    • 控制器过滤器
    • 全局过滤器

核心概念

  • 控制器(ontrollers)
    • 处理请求
  • 服务(Services)
    • 数据访问和核心逻辑
  • 模块(Modules)
    • 组合所有的逻辑代码
  • 管道(Pipes)
    • 检验请求数据
  • 过滤器(filters)
    • 处理请求时的错误
  • 守卫(Guards)
    • 鉴权和认证
  • 拦截器(Interceptors)
    • 给请求和响应加入额外的逻辑
  • 存储库(Repositores)
    • 数据库中的数据处理

@nestjs/config配置文件

pnpm i -S @nestjs/config
  1. 根目录建立.env文件

以键值对方式存储

HOST = host
PORT = port
  1. app.module.ts导入
#!app.module.ts
import {ConfigModule} from "@nestjs/config";
import Module from "@nestjs/common"

@Module({
  imports: [ConfigModule.forRoot({
    isGlobal: true,// 是否全局使用
    envFilePath: ".env.velopment",// 设置特定的配置文件
    loag:[() => {
        return dotenv.config({path: '.env'})// 加载其他配置文件,但是上面的配置会覆盖下面已存在的配置,都配置同一个变量名,上面的生效
    }]
  })]
})

  1. user.controller.ts使用
import { ConfigService } from "@nestjs/config"

@Controller('user')
export class UserController{
    constructor(private configService: ConfigService){
        
    }
    @Get()
    getUser(): string{
        console.log(this.configService.get(DB))
        return "Hello"
    }
}
  1. 使用枚举使用参数

建立enmu文件

export enum ConfigEnum{
    DB = "DB",
    HOST = "HOST",
}

我可以使用js文件来定义配置文件 使用load方法

数据库

ORM

  • ORM(Object Relational Mapping)对象关系映射,将对象概念和数据库联系起来

数据库设计参考

open.yespi.cn/list.html

使用TypeORM

安装

pnpm i -S @nestjs/typeorm typeorm mysql2

导入

#!app.module.ts
import Module from "@nestjs/common";
import { TypeOrmMoudle } from "@nestjs/typeorm"

@Module({
  imports: [TypeOrmModule.forRoot({
    type:"mysql",
    host:"localhost",
    port:3306,
    username:"root",
    password:"root",
    database:"dbname",
    entities:[],
    synchronize: true,//同步本地的cchema与数据库 ,初始化使用,
    logging: ['error'],// 日志等级
    
  })]
})