@buka/nestjs-kit 3.0.1 → 4.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,331 @@
1
+ # Core 模块
2
+
3
+ ## 概述
4
+
5
+ Core 模块是 `@buka/nestjs-kit` 的基础模块,提供全局验证管道、UUIDv7 校验管道、分页查询、Model 装饰器体系、类型转换工具,以及公司级统一资源名称(URN)工具类。
6
+
7
+ ```typescript
8
+ import {
9
+ BukaModule,
10
+ PageQuery,
11
+ OptionalPageQuery,
12
+ Slice,
13
+ OffsetPagination,
14
+ CursorPagination,
15
+ } from "@buka/nestjs-kit";
16
+ ```
17
+
18
+ ---
19
+
20
+ ## BukaModule
21
+
22
+ 全局模块,通过 `BukaModule.register()` 注册,自动为应用提供全局 `BukaValidationPipe`。
23
+
24
+ ### 基本用法
25
+
26
+ ```typescript
27
+ import { Module } from "@nestjs/common";
28
+ import { BukaModule } from "@buka/nestjs-kit";
29
+
30
+ @Module({
31
+ imports: [BukaModule.register({})],
32
+ })
33
+ export class AppModule {}
34
+ ```
35
+
36
+ ### 自定义验证选项
37
+
38
+ `BukaModule.register()` 接受 `BukaModuleOptions` 参数:
39
+
40
+ ```typescript
41
+ interface BukaModuleOptions {
42
+ validation?: ValidationPipeOptions;
43
+ }
44
+ ```
45
+
46
+ ```typescript
47
+ BukaModule.register({
48
+ validation: {
49
+ whitelist: true,
50
+ forbidNonWhitelisted: true,
51
+ },
52
+ });
53
+ ```
54
+
55
+ ### 异步注册
56
+
57
+ ```typescript
58
+ BukaModule.registerAsync({
59
+ useFactory: () => ({
60
+ validation: {
61
+ whitelist: true,
62
+ },
63
+ }),
64
+ });
65
+ ```
66
+
67
+ - 不传 `validation` 时,使用 `BukaValidationPipe` 的默认配置
68
+ - 传入 `validation` 时,将选项传递给 `BukaValidationPipe` 构造函数
69
+
70
+ ---
71
+
72
+ ## 分页查询装饰器
73
+
74
+ ### @PageQuery(mode?)
75
+
76
+ 控制器方法参数装饰器,从 `query.page` 中解析分页参数,自动注册 Swagger 文档。
77
+
78
+ ```typescript
79
+ import { PageQuery, OptionalPageQuery, IPageQuery } from "@buka/nestjs-kit";
80
+ ```
81
+
82
+ **参数**
83
+
84
+ | 参数 | 类型 | 说明 |
85
+ | ------ | ---------------------- | ------------------------------------------ |
86
+ | `mode` | `'cursor' \| 'offset'` | 可选。限制分页模式,不传则同时支持两种模式 |
87
+
88
+ **示例**
89
+
90
+ ```typescript
91
+ import { Controller, Get } from "@nestjs/common";
92
+ import { PageQuery, IPageQuery } from "@buka/nestjs-kit";
93
+
94
+ @Controller("users")
95
+ export class UserController {
96
+ @Get()
97
+ findAll(@PageQuery("offset") page: IPageQuery<"offset">) {
98
+ // page.page === { limit: 10, offset: 0 }
99
+ }
100
+ }
101
+ ```
102
+
103
+ ### @OptionalPageQuery(mode?)
104
+
105
+ 与 `@PageQuery` 相同,但分页参数为可选。当客户端不传 `page` 查询参数时不会报错。
106
+
107
+ ```typescript
108
+ @Get()
109
+ findAll(@OptionalPageQuery('cursor') page?: IPageQuery<'cursor'>) {
110
+ // page 可能为 undefined
111
+ }
112
+ ```
113
+
114
+ ### 分页参数类型
115
+
116
+ ```typescript
117
+ // 偏移分页
118
+ type IOffsetPageParameters = {
119
+ limit: number
120
+ offset: number
121
+ }
122
+
123
+ // 游标分页(向后翻页)
124
+ type INextCursorPageParameters = {
125
+ first: number
126
+ after: string
127
+ }
128
+
129
+ // 游标分页(向前翻页)
130
+ type IPreviousCursorPageParameters = {
131
+ last: number
132
+ before: string
133
+ }
134
+
135
+ // 统一分页查询类型
136
+ type IPageQuery<T extends 'cursor' | 'offset'> = {
137
+ page: /* 根据 T 推导具体类型 */
138
+ }
139
+ ```
140
+
141
+ ---
142
+
143
+ ## 请求来源装饰器
144
+
145
+ ### @IsBrowserRequest()
146
+
147
+ 控制器方法参数装饰器,通过检测请求头中是否携带 [`Sec-Fetch-*` 系列头](https://www.w3.org/TR/fetch-metadata/),判断当前请求是否来自浏览器,为装饰的参数注入 `boolean` 值。
148
+
149
+ > **原理**:W3C _Fetch Metadata Request Headers_ 规范规定,浏览器在每次发起请求时须自动附加 `Sec-Fetch-Site`、`Sec-Fetch-Mode`、`Sec-Fetch-Dest` 等头。非浏览器客户端(如 curl、Postman、服务端对服务端调用)通常不携带这些头,因此可以此作为区分依据。
150
+
151
+ ```typescript
152
+ import { IsBrowserRequest } from "@buka/nestjs-kit";
153
+ ```
154
+
155
+ **示例**
156
+
157
+ ```typescript
158
+ import { Controller, Get } from "@nestjs/common";
159
+ import { IsBrowserRequest } from "@buka/nestjs-kit";
160
+
161
+ @Controller("users")
162
+ export class UserController {
163
+ @Get("me")
164
+ getMe(@IsBrowserRequest() isBrowser: boolean) {
165
+ if (isBrowser) {
166
+ // 浏览器请求,可返回需要前端渲染的完整数据结构
167
+ } else {
168
+ // API 工具 / 服务端调用,可按机器可读格式返回
169
+ }
170
+ }
171
+ }
172
+ ```
173
+
174
+ **返回值**
175
+
176
+ | 场景 | 值 |
177
+ | ------------------------------------------- | ------- |
178
+ | 请求头中存在任意 `Sec-Fetch-*` 头(浏览器) | `true` |
179
+ | 请求头中不存在任何 `Sec-Fetch-*` 头 | `false` |
180
+
181
+ **注意事项**
182
+
183
+ - 检测是大小写不敏感的(`sec-fetch-mode` 与 `Sec-Fetch-Mode` 均可触发)
184
+ - 此装饰器仅适用于 HTTP 传输协议,WebSocket 等其他传输协议需自行处理
185
+ - 客户端可手动添加 `Sec-Fetch-*` 头来伪造浏览器请求;请勿将此装饰器用于安全鉴权,仅适合用于内容格式差异化等非安全敏感场景
186
+
187
+ ---
188
+
189
+ ## 分页模型
190
+
191
+ ### Slice\<T\>
192
+
193
+ 分页数据的统一容器,包含数据列表和分页信息。支持迭代器协议和 `map` 操作。
194
+
195
+ ```typescript
196
+ import { Slice, OffsetPagination, CursorPagination } from "@buka/nestjs-kit";
197
+ ```
198
+
199
+ **静态工厂方法**
200
+
201
+ | 方法 | 说明 |
202
+ | ------------------------------------------- | --------------------------------- |
203
+ | `Slice.fromOffset(data, total, parameters)` | 从偏移分页结果创建 Slice |
204
+ | `Slice.fromCursor(cursor)` | 从 MikroORM Cursor 对象创建 Slice |
205
+
206
+ **实例方法**
207
+
208
+ | 方法 | 说明 |
209
+ | --------------------- | -------------------------------------------- |
210
+ | `map(fn)` | 映射数据列表,返回新的 Slice(保留分页信息) |
211
+ | `[Symbol.iterator]()` | 支持 `for...of` 遍历 |
212
+
213
+ **示例**
214
+
215
+ ```typescript
216
+ // 偏移分页
217
+ const slice = Slice.fromOffset(users, 100, { limit: 10, offset: 0 });
218
+
219
+ // 游标分页(配合 MikroORM)
220
+ const cursor = await em.findByCursor(
221
+ UserEntity,
222
+ {},
223
+ { first: 10, after: "..." },
224
+ );
225
+ const slice = Slice.fromCursor(cursor);
226
+
227
+ // 映射
228
+ const dtoSlice = slice.map((user) => new UserDto(user));
229
+ ```
230
+
231
+ ### OffsetPagination
232
+
233
+ 偏移分页信息模型。
234
+
235
+ | 属性 | 类型 | 说明 |
236
+ | -------- | -------- | -------- |
237
+ | `total` | `number` | 总数 |
238
+ | `limit` | `number` | 每页数量 |
239
+ | `offset` | `number` | 偏移量 |
240
+
241
+ ### CursorPagination
242
+
243
+ 游标分页信息模型。
244
+
245
+ | 属性 | 类型 | 说明 |
246
+ | ------------- | ---------------- | ------------ |
247
+ | `total` | `number?` | 总数(可选) |
248
+ | `limit` | `number` | 每页数量 |
249
+ | `startCursor` | `string \| null` | 开始游标 |
250
+ | `endCursor` | `string \| null` | 结束游标 |
251
+ | `hasNextPage` | `boolean` | 是否有下一页 |
252
+ | `hasPrevPage` | `boolean` | 是否有上一页 |
253
+
254
+ ---
255
+
256
+ ## ParseUUIDv7Pipe
257
+
258
+ 参数级 Pipe,校验路由参数是否为合法的 UUIDv7 格式。校验失败时抛出 `BadRequestException`,行为与 NestJS 内置 `ParseUUIDPipe` 一致。
259
+
260
+ ```typescript
261
+ import { ParseUUIDv7Pipe } from "@buka/nestjs-kit";
262
+ ```
263
+
264
+ **使用示例**
265
+
266
+ ```typescript
267
+ import { Controller, Get, Param } from "@nestjs/common";
268
+ import { ParseUUIDv7Pipe } from "@buka/nestjs-kit";
269
+
270
+ @Controller("users")
271
+ export class UserController {
272
+ @Get(":id")
273
+ findOne(@Param("id", ParseUUIDv7Pipe) id: string) {
274
+ // id 已保证为合法的 UUIDv7
275
+ }
276
+ }
277
+ ```
278
+
279
+ **校验规则**
280
+
281
+ - 必须为合法 UUID 格式
282
+ - UUID 版本必须为 7
283
+ - 不满足条件时抛出 `BadRequestException('Validation failed (UUIDv7 is expected)')`
284
+
285
+ ---
286
+
287
+ ## Class Validator 装饰器
288
+
289
+ Core 模块提供了几个自定义的 class-validator 装饰器:
290
+
291
+ ### @HasAnyKey(keys)
292
+
293
+ 验证对象是否包含指定 key 列表中的至少一个。
294
+
295
+ ```typescript
296
+ import { HasAnyKey } from "@buka/nestjs-kit";
297
+
298
+ class UpdateDto {
299
+ @HasAnyKey(["name", "email", "age"])
300
+ data: Record<string, any>;
301
+ }
302
+ ```
303
+
304
+ ### @MatchJsonSchema(schema)
305
+
306
+ 验证属性值是否匹配给定的 JSON Schema。
307
+
308
+ ```typescript
309
+ import { MatchJsonSchema } from "@buka/nestjs-kit";
310
+
311
+ class ConfigDto {
312
+ @MatchJsonSchema({
313
+ type: "object",
314
+ properties: { host: { type: "string" } },
315
+ required: ["host"],
316
+ })
317
+ database: any;
318
+ }
319
+ ```
320
+
321
+ ### IsScalar(ctor, each)
322
+
323
+ 内部工具函数,根据标量类型(`String` / `Number` / `Boolean`)返回对应的 class-validator 装饰器。
324
+
325
+ ---
326
+
327
+ ## 更多文档
328
+
329
+ - [Model 装饰器体系](./models.md) — `@Model()`、`@Property()`、`@Composite()`、`@List()`、`@Dictionary()` 等
330
+ - [类型转换工具](./converters.md) — `PickType`、`OmitType`、`PartialType`、`ResponseBodyType`、`@FilterQuery` 等
331
+ - [URN 统一资源名称](./urn.md) — `Urn`、`NamespaceUrn`、`ResourceUrn`、`IdentifierUrn`、`@IsUrn()` 等
@@ -0,0 +1,303 @@
1
+ # Model 装饰器体系
2
+
3
+ ## 概述
4
+
5
+ `@buka/nestjs-kit` 提供了一套声明式的 Model 装饰器体系,用于统一描述数据模型的结构。核心流程为:
6
+
7
+ 1. **`@Model()`** 注册一个类为模型,建立元数据容器,并可配置 schema 级属性
8
+ 2. **属性装饰器**(`@Property`、`@Composite`、`@List`、`@Dictionary`)描述每个字段的类型与结构
9
+ 3. 属性装饰器内部自动应用 **class-validator** 验证规则和 **Swagger (`@ApiProperty`)** 文档注解
10
+
11
+ 这一设计让开发者只需编写一次装饰器声明,即可同时获得运行时校验与 API 文档生成能力。
12
+
13
+ ## @Model()
14
+
15
+ 类级别装饰器,将目标类注册到 `ModelRegister` 元数据中心,并可通过选项配置 schema 级属性。
16
+
17
+ ### 选项
18
+
19
+ | 选项 | 类型 | 说明 |
20
+ | --- | --- | --- |
21
+ | `schema` | `ModelSchemaOptions` | 配置 Swagger/OpenAPI schema 级属性,仅影响文档生成 |
22
+ | `additionalProperties` | `boolean \| (() => Class<object>)` | 控制序列化时是否保留未注册的额外字段 |
23
+
24
+ `ModelSchemaOptions` 支持的字段:
25
+
26
+ | 字段 | 类型 | 说明 |
27
+ | --- | --- | --- |
28
+ | `description` | `string` | schema 的描述信息 |
29
+ | `additionalProperties` | `boolean` | 控制 OpenAPI schema 是否允许额外属性(仅文档) |
30
+
31
+ **`additionalProperties` 选项说明**
32
+
33
+ | 值 | 序列化行为 |
34
+ | --- | --- |
35
+ | 未设置(默认) | 仅输出通过 `@Property`/`@Composite` 等装饰器注册的字段,额外字段被丢弃 |
36
+ | `true` | 额外字段原样保留到序列化结果中 |
37
+ | `() => SomeModel` | 额外字段按指定 Model 类型递归序列化 |
38
+
39
+ > 注意:`additionalProperties` 是 `ModelOptions` 的顶级属性,影响运行时序列化行为;`schema.additionalProperties` 是 `ModelSchemaOptions` 的子属性,仅影响 OpenAPI 文档。两者独立配置、互不影响。
40
+
41
+ ### 示例
42
+
43
+ ```typescript
44
+ import { Model, Property } from '@buka/nestjs-kit'
45
+
46
+ // 基础用法
47
+ @Model()
48
+ class UserProfile {
49
+ @Property() name!: string
50
+ }
51
+
52
+ // 禁止额外属性(仅 OpenAPI 文档)
53
+ @Model({ schema: { additionalProperties: false } })
54
+ class CreateUserDto {
55
+ @Property() name!: string
56
+ @Property() email!: string
57
+ }
58
+
59
+ // 序列化时保留额外字段
60
+ @Model({ additionalProperties: true })
61
+ class DynamicConfig {
62
+ @Property() version!: string
63
+ // 其他动态字段在序列化时会被原样保留
64
+ }
65
+
66
+ // 额外字段按指定类型递归序列化
67
+ @Model({ additionalProperties: () => MetricValue })
68
+ class MetricsMap {
69
+ @Property() timestamp!: string
70
+ // 其他字段会按 MetricValue 的 @Model 元数据递归序列化
71
+ }
72
+ ```
73
+
74
+ 注册后可通过 `ModelRegister.isModel(UserProfile)` 判断该类是否为已注册模型。
75
+
76
+ > 属性装饰器(`@Property` 等)在调用时会自动执行 `addModel`,因此即使省略 `@Model()`,只要使用了属性装饰器,类也会被隐式注册。但建议始终显式标注 `@Model()` 以提高可读性。
77
+
78
+ > `schema` 和 `additionalProperties` 配置**不会**被 `PartialType`、`PickType`、`OmitType`、`IntersectionType` 等 converter 继承。如需在派生类上设置这些选项,应在派生类上直接声明。
79
+
80
+ ## @Property()
81
+
82
+ 用于标量属性(`string`、`number`、`boolean` 等基本类型)。
83
+
84
+ ### 选项
85
+
86
+ | 选项 | 类型 | 默认值 | 说明 |
87
+ | --- | --- | --- | --- |
88
+ | `optional` | `boolean` | `false` | 标记为可选字段,自动应用 `@IsOptional()` |
89
+ | `schema` | `ApiPropertyOptions` | — | 传递给 `@ApiProperty` / `@ApiPropertyOptional` 的 Swagger 配置 |
90
+
91
+ ### 示例
92
+
93
+ ```typescript
94
+ import { Model, Property } from '@buka/nestjs-kit'
95
+
96
+ @Model()
97
+ class UserProfile {
98
+ @Property({ schema: { type: 'string', description: '用户名' } })
99
+ name: string
100
+
101
+ @Property({ optional: true, schema: { type: 'number' } })
102
+ age?: number
103
+ }
104
+ ```
105
+
106
+ ### 自动应用的装饰器
107
+
108
+ - `optional: true` → `@IsOptional()` + `@ApiPropertyOptional(schema)`
109
+ - `optional: false`(默认)→ `@ApiProperty(schema)`(仅当提供了 `schema` 时)
110
+
111
+ ## @Composite()
112
+
113
+ 用于嵌套单个复合对象的属性。
114
+
115
+ ### 选项
116
+
117
+ | 选项 | 类型 | 必填 | 说明 |
118
+ | --- | --- | --- | --- |
119
+ | `type` | `() => Class<object>` | 是 | 返回嵌套对象的类(使用惰性函数避免循环引用) |
120
+ | `optional` | `boolean` | 否 | 标记为可选,默认 `false` |
121
+ | `schema` | `ApiPropertyOptions` | 否 | Swagger 配置,默认使用 `{ type: () => options.type() }` |
122
+ | `association` | `AssociationMetadata` | 否 | 关联元数据,用于描述 ORM 关系 |
123
+
124
+ ### 示例
125
+
126
+ ```typescript
127
+ import { Model, Composite } from '@buka/nestjs-kit'
128
+
129
+ @Model()
130
+ class Order {
131
+ @Composite({ type: () => Address })
132
+ shippingAddress: Address
133
+
134
+ @Composite({ type: () => Address, optional: true })
135
+ billingAddress?: Address
136
+ }
137
+ ```
138
+
139
+ ### 自动应用的装饰器
140
+
141
+ - `@ValidateNested()` — 递归校验嵌套对象
142
+ - `@Type(() => TargetClass)` — class-transformer 类型标注
143
+ - 必填时 → `@IsNotEmpty()` + `@ApiProperty(schema)`
144
+ - 可选时 → `@IsOptional()` + `@ApiPropertyOptional(schema)`
145
+
146
+ ## @List()
147
+
148
+ 用于数组属性,支持**标量数组**和**对象数组**两种场景。
149
+
150
+ ### 选项
151
+
152
+ | 选项 | 类型 | 必填 | 说明 |
153
+ | --- | --- | --- | --- |
154
+ | `type` | `(() => Class<object>)` \| `ScalarClass` | 是 | 数组元素类型。标量传 `String` / `Number` / `Boolean`;对象传惰性函数 |
155
+ | `optional` | `boolean` | 否 | 标记为可选,默认 `false` |
156
+ | `schema` | `ApiPropertyOptions` | 否 | Swagger 配置 |
157
+ | `association` | `AssociationMetadata` | 否 | 关联元数据 |
158
+
159
+ ### 标量数组示例
160
+
161
+ ```typescript
162
+ @Model()
163
+ class TaggedItem {
164
+ @List({ type: String })
165
+ tags: string[]
166
+ }
167
+ ```
168
+
169
+ 自动应用:`@IsArray()` + `@IsString({ each: true })` + `@ApiProperty({ type: String, isArray: true })`
170
+
171
+ ### 对象数组示例
172
+
173
+ ```typescript
174
+ @Model()
175
+ class Order {
176
+ @List({ type: () => OrderItem })
177
+ items: OrderItem[]
178
+ }
179
+ ```
180
+
181
+ 自动应用:`@ValidateNested({ each: true })` + `@Type(() => OrderItem)` + `@ApiProperty({ type: () => OrderItem, isArray: true })`
182
+
183
+ ## @Dictionary()
184
+
185
+ 用于字典属性,支持 `Record<string, T>`(默认)和 `Map<string, T>` 两种模式,以及**无类型字典**、**标量字典**和**对象字典**三种场景。
186
+
187
+ ### 选项
188
+
189
+ | 选项 | 类型 | 必填 | 说明 |
190
+ | --- | --- | --- | --- |
191
+ | `type` | `(() => Class<object>)` \| `ScalarClass` | 否 | 值类型。不指定时仅校验为对象 |
192
+ | `optional` | `boolean` | 否 | 标记为可选,默认 `false` |
193
+ | `map` | `boolean` | 否 | 启用 Map 模式,默认 `false`。见下方 [Record vs Map 模式](#record-vs-map-模式) |
194
+ | `schema` | `ApiPropertyOptions` | 否 | Swagger 配置 |
195
+ | `association` | `AssociationMetadata` | 否 | 关联元数据 |
196
+
197
+ ### Record vs Map 模式
198
+
199
+ `@Dictionary` 默认以 `Record<string, T>`(普通对象)方式工作。设置 `map: true` 可切换为 `Map<string, T>` 模式。
200
+
201
+ | 特性 | Record 模式(默认) | Map 模式(`map: true`) |
202
+ | --- | --- | --- |
203
+ | 数据类型 | 普通对象 `{ key: value }` | `Map<string, T>` |
204
+ | 验证方式 | 自定义验证器遍历 `Object.values()` | class-validator 原生 `{ each: true }` |
205
+ | 嵌套错误路径 | 顶层错误信息 | 完整嵌套路径(如 `addresses.home.city`) |
206
+ | 适用场景 | JSON 序列化/反序列化、REST API | 需要完整嵌套验证错误路径时 |
207
+
208
+ ### 标量字典示例
209
+
210
+ ```typescript
211
+ @Model()
212
+ class Config {
213
+ // Record 模式(默认)— 接收普通对象 { key: "value" }
214
+ @Dictionary({ type: String })
215
+ labels: Record<string, string>
216
+
217
+ // Map 模式 — 接收 Map<string, number>
218
+ @Dictionary({ type: Number, map: true })
219
+ metrics: Map<string, number>
220
+ }
221
+ ```
222
+
223
+ **Record 模式自动应用:** `@IsObject()` + `@IsScalarDictionary(String)` + `@ApiProperty({ type: 'object', additionalProperties: { type: 'string' } })`
224
+
225
+ **Map 模式自动应用:** `@IsObject()` + `@IsString({ each: true })` + `@ApiProperty({ type: 'object', additionalProperties: { type: 'string' } })`
226
+
227
+ ### 对象字典示例
228
+
229
+ ```typescript
230
+ @Model()
231
+ class Warehouse {
232
+ // Record 模式(默认)
233
+ @Dictionary({ type: () => Stock })
234
+ stockByRegion: Record<string, Stock>
235
+
236
+ // Map 模式
237
+ @Dictionary({ type: () => Stock, map: true })
238
+ stockMap: Map<string, Stock>
239
+ }
240
+ ```
241
+
242
+ **Record 模式自动应用:** `@IsObject()` + `@Transform(...)` + `@ValidateNestedDictionary(() => Stock)` + `@ApiProperty({ type: 'object', additionalProperties: true })`
243
+
244
+ **Map 模式自动应用:** `@ValidateNested({ each: true })` + `@Type(() => Stock)` + `@ApiProperty({ type: 'object', additionalProperties: true })`
245
+
246
+ > **提示:** Record 模式下复合类型的验证错误为顶层消息(如 `each value in stockByRegion must be a valid nested object`),不包含嵌套字段路径。如需完整的嵌套错误路径,可使用 `map: true` 模式。
247
+
248
+ ## Association 元数据
249
+
250
+ `AssociationMetadata` 用于在模型属性上附加实体间的关联信息,主要由 MikroORM 关系装饰器自动设置。
251
+
252
+ ```typescript
253
+ interface AssociationMetadata {
254
+ kind: AssociationKind // '1:1' | '1:m' | 'm:1' | 'm:n'
255
+ type: () => Class<object>
256
+ }
257
+ ```
258
+
259
+ ### AssociationKind 含义
260
+
261
+ | Kind | 含义 | 对应 ORM 装饰器 | 属性装饰器 |
262
+ | --- | --- | --- | --- |
263
+ | `1:1` | 一对一 | `@OneToOne()` | `@Composite()` |
264
+ | `1:m` | 一对多 | `@OneToMany()` | `@List()` |
265
+ | `m:1` | 多对一 | `@ManyToOne()` | `@Composite()` |
266
+ | `m:n` | 多对多 | `@ManyToMany()` | `@List()` |
267
+
268
+ 在业务层无需手动设置 `association`,它由 ORM 关系装饰器自动注入。查询关联信息时可通过 `ModelRegister.getProperty()` 获取。
269
+
270
+ ## ModelRegister
271
+
272
+ `ModelRegister` 是元数据注册中心,基于 `reflect-metadata` 存储和检索模型与属性信息。
273
+
274
+ ### 常用静态方法
275
+
276
+ | 方法 | 说明 |
277
+ | --- | --- |
278
+ | `addModel(target)` | 注册类为模型,返回 `ModelMetadata`(幂等) |
279
+ | `getModel(target)` | 获取模型元数据,未注册时返回 `undefined` |
280
+ | `isModel(target)` | 判断类是否已注册为模型 |
281
+ | `addProperty(target, key, metadata)` | 注册属性元数据(同时自动注册模型) |
282
+ | `getProperty(target, key)` | 获取单个属性的元数据 |
283
+ | `getModelPropertyKeys(target)` | 获取模型所有已注册属性的 key 列表 |
284
+ | `getProperties(target)` | 获取模型所有属性的 `PropertyMetadata[]` |
285
+ | `setProperty(target, key, metadata)` | 直接设置属性元数据(底层方法) |
286
+ | `copyProperty(source, target, key)` | 将属性元数据从一个模型复制到另一个 |
287
+
288
+ ### 示例
289
+
290
+ ```typescript
291
+ import { ModelRegister } from '@buka/nestjs-kit'
292
+
293
+ // 判断是否为模型
294
+ ModelRegister.isModel(UserProfile) // true
295
+
296
+ // 获取所有属性 key
297
+ ModelRegister.getModelPropertyKeys(UserProfile) // ['name', 'age']
298
+
299
+ // 获取单个属性的元数据
300
+ const meta = ModelRegister.getProperty(UserProfile, 'name')
301
+ // { kind: 'scalar', optional: false }
302
+ ```
303
+