# nest-base-demo **Repository Path**: huangjunHB/nest-base-demo ## Basic Information - **Project Name**: nest-base-demo - **Description**: 学习记录 nestjs - **Primary Language**: Unknown - **License**: Not specified - **Default Branch**: main - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2026-01-01 - **Last Updated**: 2026-01-01 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # Nestjs 学习 ## 相关前置知识 ### Ts装饰器(decorator) 使用ts装饰器 `tsconfig.json` 中开启`experimentalDecorators:true` 如 ```ts // tsconfig.json { "compilerOptions": { "emitDecoratorMetadata": true, // 使用元数据需要开启 "experimentalDecorators": true // 使用装饰器需要开启 } } ``` - 类装饰器 ```ts const singleton = (constructor) => { let instance: unknown; console.log('before run constructor'); return class extends constructor { constructor(...args: any[]) { if (instance) return instance; super(...args); instance = this; } }; }; @singleton class User {} const user1 = new User(); const user2 = new User(); console.log(user1 === user2); // true ``` - 方法装饰器 - 属性装饰器 ```ts const maxLength = (num: number) => { return (target, propertyKey) => { // 只负责登记 Reflect.defineMetadata('MAX_LENGTH', num, target, propertyKey); }; }; class User { @maxLength(20) name: string; } const length = Reflect.getMetadata('MAX_LENGTH', User.prototype, 'name'); console.log(length); // 20 ``` - 参数装饰器 ### Ts元数据(metadata) metadata(元数据) 是指附加到类、方法、属性等上的运行时可读取的额外信息 - 基本使用 ```ts import 'reflect-metadata'; class User {} Reflect.defineMetadata('CLASS', { name: 'ls', age: 20 }, User); Reflect.defineMetadata( 'PROPERTY_OR_METHOD', { name: 'zs', age: 18 }, User, 'key', ); const data = Reflect.getMetadata('CLASS', User); const data1 = Reflect.getMetadata('PROPERTY_OR_METHOD', User, 'key'); const data2 = Reflect.getMetadata('PROPERTY_OR_METHOD', User); console.log(data); // { name: 'ls', age: 20 } console.log(data1); // { name: 'zs', age: 18 } console.log(data2); // undefined ``` - 元数据与装饰器使用 装饰器的形参与元数据api真是太契合了!~😄 ```ts const testClass = (constructor) => { Reflect.defineMetadata('TEST_CLASS', { name: 'ww', age: 20 }, constructor); }; @testClass class Student { name: string; age: number; constructor(studentName: string, studentAge: number) { this.name = studentName; this.age = studentAge; } } // 获取元数据 const data3 = Reflect.getMetadata('TEST_CLASS', Student); console.log(data3); // { name: 'ww', age: 20 } ``` - 语法糖🍬 ```ts @Reflect.metadata('TEACHERCLASS', { type: 'Class Teacher' }) class Teacher { @Reflect.metadata('TEACHERPROPERTY', { type: 'Property name' }) name: string; } // 获取数据 const data4 = Reflect.getMetadata('TEACHERCLASS', Teacher); const data5 = Reflect.getMetadata('TEACHERPROPERTY', Teacher.prototype, 'name') console.log(data4); // { type: 'Class Teacher' } console.log(data5); // { type: 'Property name' } ``` ## 内置哪些装饰器(Decorator) ## 中间件(Middleware) ## 异常过滤器(ExceptionFilter) ## 拦截器(NestInterceptor) ## 管道(Pipe) ## 守卫(Guard)