七、IOC的基础:emitDecoratorMetadata

emitDecoratorMetadata是一个tsconfig的配置项,它是nestjs实现IOC容器依赖注入的核心。

TS里,emitDecoratorMetadata生成元数据主要有以下三种:

  • design: type 用于 属性的类型元数据
  • design: paramtypes 用于 构造函数/方法 参数的类型元数据
  • design: returntype 用于 方法的返回类型元数据

示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import 'reflect-metadata'

function classDecorator(target) {}

function parameterDecorator(target, propertyKey, parameterIndex) {}

function propDecorator(target, propertyKey) {}

function methodDecorator(target, propertyKey, descriptor) {}

@classDecorator
class Example {

@propDecorator
myProperty: string

constructor(@parameterDecorator serviceA: string, @parameterDecorator serviceB: string) {}

@methodDecorator
myMethod(): string {
return 'hello'
}
}

// 属性的类型
const propertyType = Reflect.getMetadata('design:type', Example.prototype, 'myProperty')
// propertyType: [Function: String] => myProperty属性的类型
console.log('propertyType:', propertyType)

// 参数的类型
const paramTypes = Reflect.getMetadata('design:paramtypes', Example)
// paramTypes: [ [Function: String], [Function: String] ] => 构造函数的两个参数的类型
console.log('paramTypes:', paramTypes)

// 方法的返回值类型
const methodReturnType = Reflect.getMetadata('design:returntype', Example.prototype, 'myMethod')
// methodReturnType: [Function: String] => myMethod返回值的类型
console.log('methodReturnType:', methodReturnType)

我们基于emitDecoratorMetadata生成的数据,就可以知道要注入容器的内容了。

作者

胡兆磊

发布于

2025-03-26

更新于

2025-04-21

许可协议