@buka/nestjs-kit 4.3.2 → 4.3.4

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.
@@ -197,6 +197,8 @@ async findOne(@Param('id') id: string): Promise<UserResponseBody> {
197
197
 
198
198
  `ResponseBodyType` 生成的类内置了 `toJSON()` 方法,在 JSON 序列化时会根据 `@Model()` 元数据递归处理 `data` 属性。对于 MikroORM 实体,已 populate 的关联会完整序列化,未 populate 的关联仅返回主键,无需手动处理。
199
199
 
200
+ > `lazy: true` 的属性(如 `OneToMany`、`ManyToMany` 集合)默认不注册 Swagger schema,因此不会出现在 Swagger schema 中。这确保了 API 类型与 `findOne()` 不加 populate 的运行时结果一致。如需在响应中包含 lazy 属性,请使用 [EntityDto](/mikro-orm#entitydto) 派生 DTO 并手动声明。详见 [懒加载属性](/core/models#懒加载属性lazy)。
201
+
200
202
  ---
201
203
 
202
204
  ### ListResponseBodyType
@@ -252,6 +254,8 @@ async findAll(): Promise<UserListResponseBody> {
252
254
 
253
255
  `ListResponseBodyType` 生成的类内置了 `toJSON()` 方法,在 JSON 序列化时会根据 `@Model()` 元数据递归处理 `data` 数组中的每个元素。对于 MikroORM 实体,已 populate 的关联会完整序列化,未 populate 的关联仅返回主键,无需手动处理。
254
256
 
257
+ > `lazy: true` 的属性(如 `OneToMany`、`ManyToMany` 集合)默认不注册 Swagger schema,因此不会出现在 Swagger schema 中。这确保了 API 类型与 `findOne()` 不加 populate 的运行时结果一致。如需在响应中包含 lazy 属性,请使用 [EntityDto](/mikro-orm#entitydto) 派生 DTO 并手动声明。详见 [懒加载属性](/core/models#懒加载属性lazy)。
258
+
255
259
  ---
256
260
 
257
261
  ## 查询转换器
@@ -118,6 +118,7 @@ class UserProfile {
118
118
  | --- | --- | --- | --- |
119
119
  | `type` | `() => Class<object>` | 是 | 返回嵌套对象的类(使用惰性函数避免循环引用) |
120
120
  | `optional` | `boolean` | 否 | 标记为可选,默认 `false` |
121
+ | `lazy` | `boolean` | 否 | 标记为懒加载属性,默认 `false`。`lazy: true` 时不注册 Swagger schema,详见[懒加载属性](#懒加载属性lazy) |
121
122
  | `schema` | `ApiPropertyOptions` | 否 | Swagger 配置,默认使用 `{ type: () => options.type() }` |
122
123
  | `association` | `AssociationMetadata` | 否 | 关联元数据,用于描述 ORM 关系 |
123
124
 
@@ -153,6 +154,7 @@ class Order {
153
154
  | --- | --- | --- | --- |
154
155
  | `type` | `(() => Class<object>)` \| `ScalarClass` | 是 | 数组元素类型。标量传 `String` / `Number` / `Boolean`;对象传惰性函数 |
155
156
  | `optional` | `boolean` | 否 | 标记为可选,默认 `false` |
157
+ | `lazy` | `boolean` | 否 | 标记为懒加载属性,默认 `false`。`lazy: true` 时不注册 Swagger schema,详见[懒加载属性](#懒加载属性lazy) |
156
158
  | `schema` | `ApiPropertyOptions` | 否 | Swagger 配置 |
157
159
  | `association` | `AssociationMetadata` | 否 | 关联元数据 |
158
160
 
@@ -267,6 +269,58 @@ interface AssociationMetadata {
267
269
 
268
270
  在业务层无需手动设置 `association`,它由 ORM 关系装饰器自动注入。查询关联信息时可通过 `ModelRegister.getProperty()` 获取。
269
271
 
272
+ ## 懒加载属性(lazy)
273
+
274
+ `lazy` 选项用于标记那些**默认不会被加载**的属性。当 `lazy: true` 时,装饰器不会为该属性注册 Swagger schema(`@ApiProperty`),因此该属性**不会出现在 API 文档中**。
275
+
276
+ ### 设计意图
277
+
278
+ Entity 的 Swagger schema 默认应与 `findOne()` **不加任何 populate** 的 `toJSON()` 结果保持一致。MikroORM 默认不加载 Collection 关系(OneToMany / ManyToMany),因此这些属性不应出现在默认的 API 类型中。
279
+
280
+ ### 哪些属性默认是 lazy 的
281
+
282
+ `Cardinality.OneToMany` 和 `Cardinality.ManyToMany` 装饰器默认设置 `lazy: true`:
283
+
284
+ ```typescript
285
+ @Entity()
286
+ export class AuthorEntity extends DiscreteEntity {
287
+ @Cardinality.OneToMany(() => BookEntity, (book) => book.author)
288
+ books = new Collection<BookEntity>(this) // lazy: true,不在 Swagger 中
289
+ }
290
+ ```
291
+
292
+ `Cardinality.ManyToOne` 和 `Cardinality.OneToOne` **不设置** `lazy: true`,因为未 populate 时它们序列化为 `{ id: "xxx" }` 主键引用,与默认查询结果一致。
293
+
294
+ ### 如何包含 lazy 属性
295
+
296
+ 需要在 API 响应中返回 lazy 属性时,使用 `EntityDto` 派生基本 DTO 后手动声明:
297
+
298
+ ```typescript
299
+ // 基本 DTO(lazy 属性自动排除,无 Collection/Ref 类型冲突)
300
+ export class AuthorBriefDto extends EntityDto(AuthorEntity) {}
301
+
302
+ // 详情 DTO(手动添加 lazy 属性)
303
+ export class AuthorDetailDto extends EntityDto(AuthorEntity) {
304
+ @List({ type: () => PrimaryKeyType(BookEntity) })
305
+ books!: PrimaryKeyTypeClass[]
306
+ }
307
+ ```
308
+
309
+ > 直接 `extends AuthorEntity` 会导致 `Collection<Book>` 与 `Book[]` 类型冲突。`EntityDto` 返回不继承实体的独立类,避免了此问题。
310
+
311
+ 同时在 Service 层显式 `populate: ['books']`,确保运行时数据与类型声明一致。
312
+
313
+ ### eager 选项
314
+
315
+ 在 `Cardinality.OneToMany` 或 `Cardinality.ManyToMany` 中设置 `eager: true` 会覆盖默认的 `lazy: true`,使该集合直接出现在 Swagger schema 中:
316
+
317
+ ```typescript
318
+ @Cardinality.OneToMany({ entity: () => BookEntity, mappedBy: 'author', eager: true })
319
+ books = new Collection<BookEntity>(this) // 出现在 Swagger 中
320
+ ```
321
+
322
+ > 不推荐使用 `eager: true`,因为每次查询都需要 populate 该集合。建议使用派生 DTO 方式按需包含。
323
+
270
324
  ## ModelRegister
271
325
 
272
326
  `ModelRegister` 是元数据注册中心,基于 `reflect-metadata` 存储和检索模型与属性信息。
package/docs/core/urn.md CHANGED
@@ -5,21 +5,22 @@
5
5
  `Urn` 是 `urn:buka` 统一资源名称的解析与操作工具类,无需注册模块即可使用。
6
6
 
7
7
  ```typescript
8
- import { Urn, DomainUrn, ResourceTypeUrn, ResourceIdUrn } from "@buka/nestjs-kit";
8
+ import { Urn } from "@buka/nestjs-kit";
9
9
  ```
10
10
 
11
11
  ## 格式
12
12
 
13
13
  ```
14
- urn:buka:<domain>:<resource-type>[:<resource-id>]
14
+ urn:buka:<domain>:<resource...>
15
15
  ```
16
16
 
17
- 三段分别对应**概念域**(资源类型定义权归属)、**资源类型**(可多级,第一级推荐用于 `env`)、**资源ID**(可选)。
17
+ - **domain**:概念域,按资源类型定义权归属划分,通常为系统名
18
+ - **resource**:domain 之后的完整资源路径(`:` 分隔,零到多段)。parser 不区分"类型"和"实例",应用层自行约定各段语义
18
19
 
19
20
  ```typescript
20
- Urn.of("galaxy"); // 概念域级
21
- Urn.of("galaxy", "principal"); // 资源类型级
22
- Urn.of("galaxy", "principal", "550e8400-e29b-..."); // 实例级
21
+ Urn.of("galaxy"); // 概念域级
22
+ Urn.of("galaxy", "auth-client:galaxy:console"); // 资源级(字符串)
23
+ Urn.of("galaxy", ["auth-client", "galaxy", "console"]); // 资源级(数组)
23
24
  ```
24
25
 
25
26
  > 格式规则详见 [URN 规范](https://github.com/buka-lib/docs.specifications/tree/main/urn)。
@@ -28,18 +29,17 @@ Urn.of("galaxy", "principal", "550e8400-e29b-..."); // 实例级
28
29
 
29
30
  ### Urn.of
30
31
 
31
- 根据参数数量创建对应层级的 URN,返回类型在编译期自动窄化。
32
+ 根据参数创建 URN。第二参数可为 `: ` 分隔的字符串或 `string[]`。
32
33
 
33
34
  ```typescript
34
- static of(domain: string): DomainUrn
35
- static of(domain: string, resourceType: string): ResourceTypeUrn
36
- static of(domain: string, resourceType: string, resourceId: string): ResourceIdUrn
35
+ static of(domain: string, resource?: string | string[]): Urn
37
36
  ```
38
37
 
39
38
  ```typescript
40
- Urn.of("galaxy"); // → DomainUrn
41
- Urn.of("galaxy", "principal"); // → ResourceTypeUrn
42
- Urn.of("galaxy", "principal", "550e8400-e29b-41d4-a716-..."); // → ResourceIdUrn
39
+ Urn.of("galaxy"); // 概念域级
40
+ Urn.of("galaxy", "principal:abc-123"); // 资源级
41
+ Urn.of("galaxy", ["principal", "abc-123"]); // 资源级(数组)
42
+ Urn.of("galaxy", ["auth-client", "galaxy", "console"]); // 多段资源路径
43
43
  ```
44
44
 
45
45
  ### Urn.parse
@@ -52,9 +52,9 @@ static parse(urn: string): Urn
52
52
 
53
53
  ```typescript
54
54
  const urn = Urn.parse("urn:buka:galaxy:principal:abc-123");
55
- urn.domain; // → 'galaxy'
56
- urn.resourceType; // → 'principal'
57
- urn.resourceId; // → 'abc-123'
55
+ urn.domain; // → 'galaxy'
56
+ urn.resource; // → 'principal:abc-123'
57
+ urn.resourceSegments; // → ['principal', 'abc-123']
58
58
 
59
59
  Urn.parse("urn:buka:galaxy:*:*").contains(urn); // true
60
60
  ```
@@ -64,25 +64,41 @@ Urn.parse("urn:buka:galaxy:*:*").contains(urn); // true
64
64
  序列化为 URN 字符串。
65
65
 
66
66
  ```typescript
67
- const urn = Urn.of("galaxy", "principal", "abc-123");
67
+ const urn = Urn.of("galaxy", ["principal", "abc-123"]);
68
68
  urn.toString(); // → 'urn:buka:galaxy:principal:abc-123'
69
69
  ```
70
70
 
71
71
  ### is
72
72
 
73
- 判断当前 URN 是否匹配指定条件。仅比较传入的参数,未传入的不参与比较。
73
+ 判断当前 URN 是否匹配指定的 domain 和 resource。仅比较传入的参数,未传入的不参与比较。
74
74
 
75
75
  ```typescript
76
- is(domain: string, resourceType?: string, resourceId?: string): boolean
76
+ is(domain: string, resource?: string): boolean
77
77
  ```
78
78
 
79
79
  ```typescript
80
80
  const urn = Urn.parse("urn:buka:galaxy:principal:abc-123");
81
81
 
82
- urn.is("galaxy"); // true
83
- urn.is("galaxy", "principal"); // true
84
- urn.is("galaxy", "principal", "abc-123"); // true
85
- urn.is("galaxy", "oauth2-client"); // false
82
+ urn.is("galaxy"); // true
83
+ urn.is("galaxy", "principal:abc-123"); // true(精确匹配 resource)
84
+ urn.is("galaxy", "principal"); // false(resource 不精确匹配)
85
+ ```
86
+
87
+ ### match
88
+
89
+ 判断当前 URN 是否匹配指定的 URN 模式(支持通配符)。
90
+
91
+ ```typescript
92
+ match(pattern: string): boolean
93
+ ```
94
+
95
+ ```typescript
96
+ const urn = Urn.parse("urn:buka:galaxy:principal:abc-123");
97
+
98
+ urn.match("urn:buka:galaxy:principal:*"); // true
99
+ urn.match("urn:buka:galaxy:principal:**"); // true
100
+ urn.match("urn:buka:galaxy:*:*"); // true
101
+ urn.match("urn:buka:galaxy:oauth2-client:*"); // false
86
102
  ```
87
103
 
88
104
  ### contains
@@ -109,62 +125,48 @@ concrete.contains(Urn.parse("urn:buka:galaxy:principal:123")); // true
109
125
  concrete.contains(Urn.parse("urn:buka:galaxy:principal:456")); // false
110
126
  ```
111
127
 
112
- ### withResourceType
128
+ ### withResource
113
129
 
114
- 从概念域级 URN 衍生出资源类型级 URN。
130
+ 从概念域级 URN 衍生出资源级 URN。
115
131
 
116
132
  ```typescript
117
- withResourceType(resourceType: string): ResourceTypeUrn
133
+ withResource(...segments: string[]): Urn
118
134
  ```
119
135
 
120
136
  ```typescript
121
- Urn.of("galaxy").withResourceType("principal"); // → ResourceTypeUrn
122
- ```
123
-
124
- ### withResourceId
125
-
126
- 从资源类型级 URN 衍生出实例级 URN。
137
+ Urn.of("galaxy").withResource("principal", "abc-123");
138
+ // → urn:buka:galaxy:principal:abc-123
127
139
 
128
- ```typescript
129
- withResourceId(resourceId: string): ResourceIdUrn
140
+ Urn.of("galaxy").withResource("auth-client", "galaxy", "console");
141
+ // → urn:buka:galaxy:auth-client:galaxy:console
130
142
  ```
131
143
 
132
- ```typescript
133
- Urn.of("galaxy", "principal").withResourceId("550e8400-..."); // → ResourceIdUrn
134
- ```
135
-
136
- ### resourceTypeSegments
144
+ ### resourceSegments
137
145
 
138
- 返回 `resourceType` 按 `:` 拆分后的层级数组。
146
+ 返回 `resource` 按 `:` 拆分后的段数组。
139
147
 
140
148
  ```typescript
141
- get resourceTypeSegments(): string[]
149
+ get resourceSegments(): string[]
142
150
  ```
143
151
 
144
152
  ```typescript
145
- Urn.parse("urn:buka:galaxy:principal:v1:table").resourceTypeSegments;
146
- // → ['principal', 'v1', 'table']
153
+ Urn.parse("urn:buka:galaxy:auth-client:galaxy:console").resourceSegments;
154
+ // → ['auth-client', 'galaxy', 'console']
147
155
  ```
148
156
 
149
- ### 类型守卫
157
+ ### isDomainUrn
150
158
 
151
- 用于 `Urn.parse()` 返回的宽类型 `Urn` 的层级窄化:
159
+ 类型守卫:判断是否为概念域级 URN(无 resource)。
152
160
 
153
161
  ```typescript
154
- isDomainUrn(): this is DomainUrn
155
- isResourceTypeUrn(): this is ResourceTypeUrn
156
- isResourceIdUrn(): this is ResourceIdUrn
162
+ isDomainUrn(): boolean
157
163
  ```
158
164
 
159
165
  ```typescript
160
- const urn = Urn.parse(token.sub);
161
-
162
- if (urn.isResourceIdUrn()) {
163
- urn.resourceId; // ✅ string,而非 string | undefined
164
- }
166
+ const urn = Urn.parse("urn:buka:galaxy");
165
167
 
166
- if (urn.isResourceTypeUrn()) {
167
- urn.withResourceId("id"); // ✅ 窄化后合法
168
+ if (urn.isDomainUrn()) {
169
+ // urn.resource 为 undefined
168
170
  }
169
171
  ```
170
172
 
@@ -175,25 +177,25 @@ if (urn.isResourceTypeUrn()) {
175
177
  ```typescript
176
178
  // 签发
177
179
  await sessionService.signAccessToken({
178
- subject: Urn.of("galaxy", "principal", principal.id).toString(),
180
+ subject: Urn.of("galaxy", ["principal", principal.id]).toString(),
179
181
  claims: { aud: Urn.of("galaxy").toString() },
180
182
  });
181
183
 
182
184
  // 消费
183
185
  const subjectUrn = Urn.parse(payload.sub);
184
- if (subjectUrn.isResourceIdUrn() && subjectUrn.is("galaxy", "principal")) {
185
- const principalId = subjectUrn.resourceId;
186
+ if (subjectUrn.match("urn:buka:galaxy:principal:*")) {
187
+ const principalId = subjectUrn.resourceSegments[1];
186
188
  }
187
189
  ```
188
190
 
189
- ### 资源类型判断
191
+ ### 资源路径判断
190
192
 
191
193
  ```typescript
192
194
  const urn = Urn.parse(session.subject);
193
195
 
194
- if (urn.is("galaxy", "principal")) {
196
+ if (urn.match("urn:buka:galaxy:principal:*")) {
195
197
  // 处理 Principal 类型
196
- } else if (urn.is("galaxy", "oauth2-client")) {
198
+ } else if (urn.match("urn:buka:galaxy:oauth2-client:*")) {
197
199
  // 处理 OAuth2 Client 类型
198
200
  }
199
201
  ```
@@ -201,8 +203,8 @@ if (urn.is("galaxy", "principal")) {
201
203
  ### 衍生复用
202
204
 
203
205
  ```typescript
204
- const principalType = Urn.of("galaxy").withResourceType("principal");
206
+ const domainUrn = Urn.of("galaxy");
205
207
 
206
- const urn1 = principalType.withResourceId(id1);
207
- const urn2 = principalType.withResourceId(id2);
208
+ const urn1 = domainUrn.withResource("principal", id1);
209
+ const urn2 = domainUrn.withResource("principal", id2);
208
210
  ```
package/docs/mikro-orm.md CHANGED
@@ -286,6 +286,8 @@ export class AuthorEntity extends DiscreteEntity {
286
286
  }
287
287
  ```
288
288
 
289
+ > `OneToMany` 默认 `lazy: true`,该集合**不会**出现在 Swagger 文档中。这与 MikroORM 默认不 populate 集合的行为一致——`findOne()` 的 `toJSON()` 结果不含未填充的 Collection。如需在响应中包含此集合,请使用 `EntityDto` 派生 DTO 并手动声明,同时显式 `populate`。详见 [EntityDto](/core/converters#entitydto) 和 [懒加载属性(lazy)](/core/models#懒加载属性lazy)。
290
+
289
291
  ### Cardinality.OneToOne — 一对一关系
290
292
 
291
293
  **场景示例**:一个用户有一份详细资料
@@ -314,11 +316,70 @@ export class BookEntity extends DiscreteEntity {
314
316
  }
315
317
  ```
316
318
 
319
+ > `ManyToMany` 默认 `lazy: true`,该集合**不会**出现在 Swagger 文档中。这与 MikroORM 默认不 populate 集合的行为一致。如需包含,请使用 `EntityDto` 派生 DTO 并手动声明,或设置 `eager: true`。详见 [EntityDto](/core/converters#entitydto) 和 [懒加载属性(lazy)](/core/models#懒加载属性lazy)。
320
+
317
321
  > 所有关系装饰器都会自动添加 Swagger 文档和验证规则,无需手动配置。
318
322
  > 当关系设置了 `hidden: true` 时,仅应用 `@ApiHideProperty()` 而不会注册模型属性元数据。
319
323
 
320
324
  ---
321
325
 
326
+ ## EntityDto
327
+
328
+ 从实体生成**无继承关系**的纯 DTO 类,用于安全派生响应类型。
329
+
330
+ ### 解决的问题
331
+
332
+ 直接 `extends` MikroORM 实体会引入 `Collection<Entity>` 类型。当你在派生 DTO 中重新声明同名字段(如 `comments: PrimaryKeyTypeClass[]`)时,TypeScript 会报类型冲突——父类的 `Collection<CommentEntity>` 与子类的 `PrimaryKeyTypeClass[]` 不兼容。
333
+
334
+ `EntityDto` 返回的类**不继承**源实体,因此不存在此冲突。同时它自动排除 `lazy: true` 的属性,Swagger schema 与 `findOne()` 不加 populate 的结果一致。
335
+
336
+ ### 类型转换
337
+
338
+ `EntityDtoShape<T>` 对实体类型做以下变换:
339
+
340
+ | 实体类型 | DTO 类型 | 原因 |
341
+ |---------|---------|------|
342
+ | `Collection<Entity>` | 键被排除 | 默认 `lazy: true`,不在 Swagger 中 |
343
+ | `Ref<Entity>` | `Ref<Entity>`(保留) | nestjs-kit 一等公民,序列化层自动处理 |
344
+ | `Xxx & Opt` | `Xxx \| undefined` | 去除 MikroORM 标记 |
345
+
346
+ ### 示例
347
+
348
+ ```typescript
349
+ import { EntityDto } from '@buka/nestjs-kit/mikro-orm'
350
+
351
+ @Entity()
352
+ class ArticleEntity extends DiscreteEntity {
353
+ @Column.Varchar({ length: 64, comment: '标题' })
354
+ title!: string
355
+
356
+ @Column.Text({ comment: '正文内容', lazy: true })
357
+ content?: string
358
+
359
+ @Cardinality.ManyToOne({ entity: () => AuthorEntity, ref: true })
360
+ author!: Ref<AuthorEntity>
361
+
362
+ @Cardinality.OneToMany({ entity: () => CommentEntity, mappedBy: 'article' })
363
+ comments = new Collection<CommentEntity>(this)
364
+ }
365
+
366
+ // 基本 DTO — 排除 content(标量 lazy)和 comments(集合 lazy)
367
+ class ArticleBriefDto extends EntityDto(ArticleEntity) {}
368
+
369
+ // 详情 DTO — 将 lazy 属性显式加回
370
+ class ArticleDetailDto extends EntityDto(ArticleEntity) {
371
+ @Property({ schema: { description: '正文内容' } })
372
+ content?: string
373
+
374
+ @List({ type: () => PrimaryKeyType(CommentEntity) })
375
+ comments!: PrimaryKeyTypeClass[]
376
+ }
377
+ ```
378
+
379
+ > `EntityDto` 是推荐的实体→响应 DTO 派生方式。对于需要选取特定字段的场景,使用 `PickType`。
380
+
381
+ ---
382
+
322
383
  ## PrimaryKeyType
323
384
 
324
385
  `PrimaryKeyType()` 工厂函数基于实体的主键字段自动生成只包含主键的 DTO 类。
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@buka/nestjs-kit",
3
- "version": "4.3.2",
3
+ "version": "4.3.4",
4
4
  "description": "Buka Nestjs Kit",
5
5
  "packageManager": "pnpm@10.33.4+sha512.1c67b3b359b2d408119ba1ed289f34b8fc3c6873412bec6fd264fbdc82489e510fcbecb9ce9d22dae7f3b76269d8441046014bdca53b9979cd7a561ad631b800",
6
6
  "types": "dist/index.d.ts",