@buka/nestjs-kit 3.0.1 → 4.1.1

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,471 @@
1
+ # MikroORM 集成
2
+
3
+ ## 简介
4
+
5
+ `@buka/nestjs-kit` 提供了一套专为 MikroORM + NestJS 项目设计的类型辅助工具集,主要解决以下痛点:
6
+
7
+ - **减少重复代码**:字段装饰器自动生成 `@nestjs/swagger` 和 `class-validator` 装饰器,一次声明即可同时获得 ORM 映射、运行时校验与 API 文档
8
+ - **开发提效**:简化实体定义、DTO 构建等常见操作
9
+
10
+ ```typescript
11
+ import { Column, Cardinality, EntityRef, BaseEntity } from '@buka/nestjs-kit/mikro-orm'
12
+ ```
13
+
14
+ ## 初始配置
15
+
16
+ ### 1. MikroORM 配置
17
+
18
+ 在 `mikro-orm.config.ts` 中启用以下配置:
19
+
20
+ ```typescript
21
+ export default defineConfig({
22
+ serialization: {
23
+ forceObject: true, // 强制将外键序列化为对象
24
+ },
25
+ forceUndefined: true, // 未定义字段返回 undefined 而非 null
26
+ // ...其他配置
27
+ })
28
+ ```
29
+
30
+ > [!TIP]
31
+ > **为什么需要 `forceObject`?**
32
+ >
33
+ > 启用后,外键会序列化为 `object` 而非 `id`。详见 [官方文档](https://mikro-orm.io/docs/serializing#foreign-keys-are-forceobject)
34
+
35
+ ### 2. Swagger CLI 插件配置(可选)
36
+
37
+ 如果使用 `@nestjs/swagger` CLI 插件,建议在 `tsconfig.json` 中配置:
38
+
39
+ ```json
40
+ {
41
+ "compilerOptions": {
42
+ "plugins": [
43
+ {
44
+ "name": "@nestjs/swagger",
45
+ "options": {
46
+ "introspectComments": true,
47
+ "dtoFileNameSuffix": [".dto.ts", ".bo.ts", ".ro.ts"]
48
+ }
49
+ }
50
+ ]
51
+ }
52
+ }
53
+ ```
54
+
55
+ > [!IMPORTANT] 不要包含 `.entity.ts`
56
+ >
57
+ > `@nestjs/swagger` 对 MikroORM 的 `Ref` 和 `Collection` 添加的装饰器是错误的。
58
+ > 为解决这个问题,请使用 `@buka/nestjs-kit` 提供的字段装饰器(如 `Column.Varchar`、`Cardinality.ManyToOne` 等)定义实体。
59
+
60
+ ---
61
+
62
+ ## 基础实体类
63
+
64
+ 所有的 Entity 都必须扩展以下基类之一,否则无法使用其他功能。
65
+
66
+ ### TimestampedEntity
67
+
68
+ **适用场景**:不需要主键 `id` 的特殊实体(如中间表、日志表等)
69
+
70
+ **包含字段**:
71
+
72
+ - `createdAt: Date` — 创建时间(自动填充 `CURRENT_TIMESTAMP`)
73
+ - `updatedAt: Date` — 更新时间(自动更新 `CURRENT_TIMESTAMP`)
74
+
75
+ **泛型参数**:`<Optional = never>` — 允许子类声明额外的可选属性
76
+
77
+ ```typescript
78
+ import { TimestampedEntity } from '@buka/nestjs-kit/mikro-orm'
79
+
80
+ @Entity()
81
+ export class UserLoginLogEntity extends TimestampedEntity {
82
+ @Column.Varchar({ length: 64 })
83
+ userId!: string
84
+
85
+ @Column.Varchar({ length: 64 })
86
+ ipAddress!: string
87
+ }
88
+ ```
89
+
90
+ ### LinearEntity
91
+
92
+ **适用场景**:需要 BigInt 自增主键的实体
93
+
94
+ **包含字段**:
95
+
96
+ - `id: string` — 主键(BigInt,以字符串形式表示,校验 `@IsNumberString()`)
97
+ - 继承 `TimestampedEntity` 的 `createdAt`、`updatedAt`
98
+
99
+ ```typescript
100
+ import { LinearEntity } from '@buka/nestjs-kit/mikro-orm'
101
+
102
+ @Entity()
103
+ export class EventLogEntity extends LinearEntity {
104
+ @Column.Varchar({ length: 256 })
105
+ message!: string
106
+ }
107
+ ```
108
+
109
+ ### DiscreteEntity(推荐)
110
+
111
+ **适用场景**:绝大多数普通实体
112
+
113
+ **包含字段**:
114
+
115
+ - `id: string` — 主键(UUID,默认使用 `uuidv7()` 生成,校验 `@IsString()`)
116
+ - 继承 `TimestampedEntity` 的 `createdAt`、`updatedAt`
117
+
118
+ ```typescript
119
+ import { DiscreteEntity } from '@buka/nestjs-kit/mikro-orm'
120
+
121
+ @Entity()
122
+ export class BookEntity extends DiscreteEntity {
123
+ @Column.Varchar({ length: 64, comment: '书名' })
124
+ name!: string
125
+ }
126
+ ```
127
+
128
+ > **建议**:99% 的实体都应该继承 `DiscreteEntity`,除非有特殊需求。
129
+
130
+ ---
131
+
132
+ ## 字段装饰器 (Column)
133
+
134
+ 所有列类型装饰器通过 `Column` 命名空间导出,每个装饰器直接对应一种数据库列类型,自动添加 Swagger 文档和验证规则。
135
+
136
+ ```typescript
137
+ import { Column } from '@buka/nestjs-kit/mikro-orm'
138
+ ```
139
+
140
+ ### 基础用法
141
+
142
+ ```typescript
143
+ import { DiscreteEntity, Column } from '@buka/nestjs-kit/mikro-orm'
144
+
145
+ @Entity()
146
+ export class BookEntity extends DiscreteEntity {
147
+ @Column.Varchar({
148
+ length: 64,
149
+ comment: '书名',
150
+ })
151
+ name!: string
152
+
153
+ @Column.Text({
154
+ comment: '书籍简介',
155
+ nullable: true,
156
+ })
157
+ description?: string
158
+
159
+ @Column.Int({
160
+ comment: '页数',
161
+ default: 0,
162
+ })
163
+ pages!: number
164
+ }
165
+ ```
166
+
167
+ ### 可用列类型
168
+
169
+ | 装饰器 | 数据库类型 | TypeScript 类型 | 自动应用的 class-validator | 说明 |
170
+ |--------|-----------|----------------|--------------------------|------|
171
+ | `Column.Varchar` | `varchar` | `string` | `@IsString()`, `@MaxLength()` | 变长字符串,支持 `length` |
172
+ | `Column.Char` | `char` | `string` | `@IsString()` | 定长字符串,支持 `length` |
173
+ | `Column.Text` | `text` | `string` | `@IsString()` | 长文本 |
174
+ | `Column.Money` | `numeric` | `string` | `@IsNumber()` | 货币类型 |
175
+ | `Column.Int` | `int` | `number` | `@IsInt()` | 32 位整数 |
176
+ | `Column.Smallint` | `smallint` | `number` | `@IsInt()` | 16 位整数 |
177
+ | `Column.Tinyint` | `tinyint` | `number` | `@IsInt()` | 8 位整数 |
178
+ | `Column.Bigint` | `bigint` | `string \| number` | `@IsString()` | 64 位整数,默认 string 模式 |
179
+ | `Column.Double` | `double` | `number` | `@IsNumber()` | 双精度浮点 |
180
+ | `Column.Numeric` | `numeric` | `number` | `@IsNumber()` | 精确数值 |
181
+ | `Column.Boolean` | `boolean` | `boolean` | `@IsBoolean()` | 布尔值 |
182
+ | `Column.Uuid` | `uuid` | `string` | `@IsUUID()` | UUID |
183
+ | `Column.Timestamptz` | `timestamptz` | `Date` | — | 带时区时间戳 |
184
+ | `Column.Enum` | `enum` | `enum` | `@IsEnum()` | 枚举 |
185
+ | `Column.Jsonb` | `jsonb` | `object` | — | JSONB |
186
+ | `Column.Transient` | — | `any` | — | 非持久化字段 |
187
+ | `Column.Embedded` | — | `object` | — | 嵌入式实体 |
188
+
189
+ ### Column.Enum — 枚举字段
190
+
191
+ ```typescript
192
+ export enum BookType {
193
+ NOVEL = 'novel',
194
+ SCIENCE = 'science',
195
+ HISTORY = 'history',
196
+ }
197
+
198
+ @Entity()
199
+ export class BookEntity extends DiscreteEntity {
200
+ @Column.Enum({
201
+ enumName: 'BOOK_TYPE',
202
+ items: () => BookType,
203
+ comment: '书籍类型',
204
+ })
205
+ type!: BookType
206
+ }
207
+ ```
208
+
209
+ ### Column.Jsonb — JSONB 字段
210
+
211
+ ```typescript
212
+ @Entity()
213
+ export class BookEntity extends DiscreteEntity {
214
+ @Column.Jsonb({
215
+ type: () => MetadataDto,
216
+ comment: '元数据',
217
+ })
218
+ metadata!: MetadataDto
219
+ }
220
+ ```
221
+
222
+ ### Column.Embedded — 嵌入式实体
223
+
224
+ ```typescript
225
+ @Entity()
226
+ export class BookEntity extends DiscreteEntity {
227
+ @Column.Embedded(() => Address)
228
+ address!: Address
229
+ }
230
+ ```
231
+
232
+ ### Column.Transient — 非持久化字段
233
+
234
+ ```typescript
235
+ @Entity()
236
+ export class BookEntity extends DiscreteEntity {
237
+ @Column.Transient()
238
+ temp!: string
239
+ }
240
+ ```
241
+
242
+ ---
243
+
244
+ ## 关系装饰器 (Cardinality)
245
+
246
+ 所有关系装饰器通过 `Cardinality` 命名空间导出,封装 MikroORM 的关系装饰器并内部调用 Model 层的 `@Composite()` 或 `@List()`,同时自动附加 `association` 元数据。
247
+
248
+ ```typescript
249
+ import { Cardinality } from '@buka/nestjs-kit/mikro-orm'
250
+ ```
251
+
252
+ ### 与 Model 层装饰器的对应关系
253
+
254
+ | 装饰器 | ORM 关系 | 内部调用 | AssociationKind |
255
+ | --- | --- | --- | --- |
256
+ | `Cardinality.OneToOne` | `@OrmOneToOne()` | `@Composite()` | `1:1` |
257
+ | `Cardinality.OneToMany` | `@OrmOneToMany()` | `@List()` | `1:m` |
258
+ | `Cardinality.ManyToOne` | `@OrmManyToOne()` | `@Composite()` | `m:1` |
259
+ | `Cardinality.ManyToMany` | `@OrmManyToMany()` | `@List()` | `m:n` |
260
+
261
+ ### Cardinality.ManyToOne — 多对一关系
262
+
263
+ **场景示例**:一本书属于一个作者
264
+
265
+ ```typescript
266
+ @Entity()
267
+ export class BookEntity extends DiscreteEntity {
268
+ @Cardinality.ManyToOne(() => AuthorEntity, {
269
+ comment: '作者',
270
+ })
271
+ author!: Ref<AuthorEntity>
272
+ }
273
+ ```
274
+
275
+ ### Cardinality.OneToMany — 一对多关系
276
+
277
+ **场景示例**:一个作者有多本书
278
+
279
+ ```typescript
280
+ @Entity()
281
+ export class AuthorEntity extends DiscreteEntity {
282
+ @Cardinality.OneToMany(() => BookEntity, (book) => book.author, {
283
+ comment: '作品列表',
284
+ })
285
+ books = new Collection<BookEntity>(this)
286
+ }
287
+ ```
288
+
289
+ ### Cardinality.OneToOne — 一对一关系
290
+
291
+ **场景示例**:一个用户有一份详细资料
292
+
293
+ ```typescript
294
+ @Entity()
295
+ export class UserEntity extends DiscreteEntity {
296
+ @Cardinality.OneToOne(() => UserProfileEntity, {
297
+ comment: '用户资料',
298
+ })
299
+ profile!: Ref<UserProfileEntity>
300
+ }
301
+ ```
302
+
303
+ ### Cardinality.ManyToMany — 多对多关系
304
+
305
+ **场景示例**:一本书可以有多个标签,一个标签可以关联多本书
306
+
307
+ ```typescript
308
+ @Entity()
309
+ export class BookEntity extends DiscreteEntity {
310
+ @Cardinality.ManyToMany(() => TagEntity, {
311
+ comment: '标签列表',
312
+ })
313
+ tags = new Collection<TagEntity>(this)
314
+ }
315
+ ```
316
+
317
+ > 所有关系装饰器都会自动添加 Swagger 文档和验证规则,无需手动配置。
318
+ > 当关系设置了 `hidden: true` 时,仅应用 `@ApiHideProperty()` 而不会注册模型属性元数据。
319
+
320
+ ---
321
+
322
+ ## PrimaryKeyType
323
+
324
+ `PrimaryKeyType()` 工厂函数基于实体的主键字段自动生成只包含主键的 DTO 类。
325
+
326
+ **使用场景**:API 请求中只需要传递关联实体的 ID 时。
327
+
328
+ ```typescript
329
+ import { PrimaryKeyType } from '@buka/nestjs-kit/mikro-orm'
330
+
331
+ // 继承 PrimaryKeyType 生成只包含主键的 DTO 类
332
+ class BookPrimaryKeyDto extends PrimaryKeyType(BookEntity) {}
333
+ ```
334
+
335
+ 工作原理:
336
+
337
+ 1. 扫描实体类的主键属性
338
+ 2. 生成包含主键属性的新类
339
+ 3. 自动复制 Swagger 元数据、class-validator 校验规则和 class-transformer 转换规则
340
+ 4. 使用 WeakMap 缓存,多次调用返回同一个类
341
+
342
+ ---
343
+
344
+ ## EntityRef
345
+
346
+ `@EntityRef()` 是 `@Composite({ type: () => PrimaryKeyType(Entity) })` 的快捷装饰器,用于在 Model 层声明实体引用(只包含主键字段)。
347
+
348
+ ```typescript
349
+ import { EntityRef } from '@buka/nestjs-kit/mikro-orm'
350
+ ```
351
+
352
+ ### 基础用法
353
+
354
+ ```typescript
355
+ import { EntityRef } from '@buka/nestjs-kit/mikro-orm'
356
+ import { IEntityPrimaryKey } from '@buka/nestjs-kit/mikro-orm'
357
+
358
+ @Model()
359
+ class CreateBookDto {
360
+ // Before
361
+ @Composite({ type: () => PrimaryKeyType(AuthorEntity) })
362
+ author: IEntityPrimaryKey<AuthorEntity>
363
+
364
+ // After — 等价写法
365
+ @EntityRef(() => AuthorEntity)
366
+ author: IEntityPrimaryKey<AuthorEntity>
367
+ }
368
+ ```
369
+
370
+ ### 选项
371
+
372
+ | 选项 | 类型 | 必填 | 说明 |
373
+ | --- | --- | --- | --- |
374
+ | `optional` | `boolean` | 否 | 标记为可选,默认 `false` |
375
+ | `schema` | `ApiPropertyOptions` | 否 | Swagger 配置 |
376
+ | `association` | `AssociationMetadata` | 否 | 关联元数据 |
377
+
378
+ ### 可选字段示例
379
+
380
+ ```typescript
381
+ @Model()
382
+ class UpdateBookDto {
383
+ @EntityRef(() => AuthorEntity, { optional: true })
384
+ author?: IEntityPrimaryKey<AuthorEntity>
385
+ }
386
+ ```
387
+
388
+ ---
389
+
390
+ ## 类型工具
391
+
392
+ `@buka/nestjs-kit/mikro-orm` 导出了一组用于处理 MikroORM 类型标记的工具类型。
393
+
394
+ | 类型 | 说明 |
395
+ | --- | --- |
396
+ | `ExcludeOpt<T>` | 移除 MikroORM 的 `Opt` 标记和 `undefined`,获取实际值类型 |
397
+ | `ExcludeRef<T>` | 解包 `Ref<T>` 得到底层实体类型;非 Ref 类型原样返回 |
398
+ | `ExcludeHidden<T>` | 移除 MikroORM 的 `Hidden` 标记 |
399
+ | `IsOpt<T>` | 布尔类型,判断 T 是否被 `Opt` 标记包裹 |
400
+ | `IsHidden<T>` | 布尔类型,判断 T 是否被 `Hidden` 标记包裹 |
401
+
402
+ ```typescript
403
+ import type { ExcludeOpt, ExcludeRef, IsHidden } from '@buka/nestjs-kit/mikro-orm'
404
+
405
+ // Ref<UserEntity> → UserEntity
406
+ type User = ExcludeRef<Ref<UserEntity>>
407
+
408
+ // string & Opt → string
409
+ type Name = ExcludeOpt<string & Opt>
410
+
411
+ // true
412
+ type Hidden = IsHidden<string & Hidden>
413
+ ```
414
+
415
+ ---
416
+
417
+ ## DatabaseConfig
418
+
419
+ `DatabaseConfig` 是数据库配置基类,配合 `@buka/nestjs-config` 使用,简化 MikroORM 的连接配置。
420
+
421
+ ### 配置属性
422
+
423
+ | 属性 | 类型 | 默认值 | 说明 |
424
+ | --- | --- | --- | --- |
425
+ | `debug` | `boolean` | `false` | 启用调试模式 |
426
+ | `migration` | `boolean` | `false` | 启用迁移支持 |
427
+ | `dbName` | `string` | — | 数据库名称(必填) |
428
+ | `host` | `string` | — | 数据库主机(必填) |
429
+ | `port` | `number` | — | 数据库端口(必填) |
430
+ | `user` | `string` | — | 数据库用户(必填) |
431
+ | `password` | `string` | — | 数据库密码(必填) |
432
+ | `timezone` | `string` | `'+08:00'` | 数据库时区 |
433
+
434
+ ### toMikroOrmOptions()
435
+
436
+ 将 `DatabaseConfig` 转换为 MikroORM `Options`,默认启用:
437
+
438
+ - `forceUndefined: true`
439
+ - `flushMode: COMMIT`
440
+ - `serialization.forceObject: true`
441
+ - 自定义错误处理(抛出 `BadRequestException`)
442
+ - 当 `migration: true` 时自动配置迁移选项
443
+
444
+ ```typescript
445
+ import * as path from 'path'
446
+ import { PostgreSqlDriver } from '@mikro-orm/postgresql'
447
+ import { Configuration } from '@buka/nestjs-config'
448
+ import { DatabaseConfig } from '@buka/nestjs-kit/mikro-orm'
449
+
450
+ const srcDir = path.resolve(__dirname, '../')
451
+
452
+ @Configuration('postgresql')
453
+ export class PostgresqlConfig extends DatabaseConfig {
454
+ toMikroOrmOptions(): Options {
455
+ let options = super.toMikroOrmOptions()
456
+
457
+ options = {
458
+ ...options,
459
+ driver: PostgreSqlDriver,
460
+ baseDir: srcDir,
461
+ entities: ['**/*.entity.js'],
462
+ migrations: {
463
+ path: path.join(srcDir, 'migrations'),
464
+ pathTs: path.join(srcDir, 'migrations'),
465
+ },
466
+ }
467
+
468
+ return options
469
+ }
470
+ }
471
+ ```
@@ -0,0 +1,193 @@
1
+ # ObjectStorageModule — 对象存储模块
2
+
3
+ ## 概述
4
+
5
+ `ObjectStorageModule` 提供 S3 兼容的对象存储客户端,基于 `@aws-sdk/client-s3` 构建。支持文件上传/下载、元数据查询、存在性检查、删除和签名 URL 生成。
6
+
7
+ ```typescript
8
+ import { ObjectStorageModule, ObjectStorageService } from '@buka/nestjs-kit'
9
+ ```
10
+
11
+ ## 模块配置
12
+
13
+ 使用 NestJS `ConfigurableModuleBuilder` 模式注册:
14
+
15
+ ```typescript
16
+ import { Module } from '@nestjs/common'
17
+ import { ObjectStorageModule } from '@buka/nestjs-kit'
18
+
19
+ @Module({
20
+ imports: [
21
+ ObjectStorageModule.register({
22
+ endpoint: 'https://s3.amazonaws.com',
23
+ bucket: 'my-bucket',
24
+ region: 'us-east-1',
25
+ accessKeyId: 'AKIAIOSFODNN7EXAMPLE',
26
+ secretAccessKey: 'wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY',
27
+ forcePathStyle: false,
28
+ prefix: 'uploads',
29
+ }),
30
+ ],
31
+ })
32
+ export class AppModule {}
33
+ ```
34
+
35
+ ### 配置选项
36
+
37
+ | 选项 | 类型 | 必填 | 默认值 | 说明 |
38
+ |------|------|------|--------|------|
39
+ | `endpoint` | `string` | 是 | — | S3 兼容服务端点 |
40
+ | `bucket` | `string` | 是 | — | 存储桶名称 |
41
+ | `region` | `string` | 是 | — | 区域 |
42
+ | `accessKeyId` | `string` | 是 | — | Access Key ID |
43
+ | `secretAccessKey` | `string` | 是 | — | Secret Access Key |
44
+ | `forcePathStyle` | `boolean` | 否 | `false` | 是否强制使用路径风格(MinIO 等兼容服务通常需要设为 `true`) |
45
+ | `prefix` | `string` | 否 | `''` | 对象键前缀,用于在同一 Bucket 下隔离不同环境或模块的数据 |
46
+
47
+ ## ObjectStorageService
48
+
49
+ ### get
50
+
51
+ 下载对象,返回可读流。
52
+
53
+ ```typescript
54
+ async get(path: string, options?: ObjectStorageOptions): Promise<Readable>
55
+ ```
56
+
57
+ ```typescript
58
+ import { Readable } from 'node:stream'
59
+
60
+ const stream: Readable = await storageService.get('documents/report.pdf')
61
+
62
+ // 流式读取
63
+ stream.pipe(res) // 直接管道到 HTTP 响应
64
+ ```
65
+
66
+ ### upload
67
+
68
+ 上传对象,支持字符串、Buffer 和可读流。基于 `@aws-sdk/lib-storage` 的 `Upload` 实现,自动处理分片上传。
69
+
70
+ ```typescript
71
+ async upload(path: string, contents: string | Readable | Buffer, options?: ObjectStorageOptions): Promise<string>
72
+ ```
73
+
74
+ 返回实际写入的对象键(可能包含 prefix)。
75
+
76
+ ```typescript
77
+ // 上传字符串
78
+ await storageService.upload('config/settings.json', JSON.stringify(config))
79
+
80
+ // 上传 Buffer
81
+ await storageService.upload('images/avatar.png', imageBuffer)
82
+
83
+ // 流式上传
84
+ import { createReadStream } from 'node:fs'
85
+ const stream = createReadStream('/path/to/large-file.zip')
86
+ await storageService.upload('backups/data.zip', stream)
87
+ ```
88
+
89
+ ### getMetadata
90
+
91
+ 获取对象的元数据。
92
+
93
+ ```typescript
94
+ async getMetadata(path: string, options?: ObjectStorageOptions): Promise<Record<string, string>>
95
+ ```
96
+
97
+ ### exists
98
+
99
+ 检查对象是否存在。
100
+
101
+ ```typescript
102
+ async exists(path: string, options?: ObjectStorageOptions): Promise<boolean>
103
+ ```
104
+
105
+ ```typescript
106
+ const fileExists = await storageService.exists('documents/report.pdf')
107
+ if (!fileExists) {
108
+ // 文件不存在
109
+ }
110
+ ```
111
+
112
+ ### remove
113
+
114
+ 删除对象。
115
+
116
+ ```typescript
117
+ async remove(path: string, options?: ObjectStorageOptions): Promise<void>
118
+ ```
119
+
120
+ ### getSignedUrl
121
+
122
+ 生成预签名 URL,用于临时授权访问私有对象。
123
+
124
+ ```typescript
125
+ async getSignedUrl(path: string, expiresInSecond: number, options?: ObjectStorageOptions): Promise<string>
126
+ ```
127
+
128
+ ```typescript
129
+ // 生成 1 小时有效期的下载链接
130
+ const url = await storageService.getSignedUrl('documents/report.pdf', 3600)
131
+ ```
132
+
133
+ ### prefix
134
+
135
+ 手动拼接 prefix 路径。
136
+
137
+ ```typescript
138
+ prefix(path: string): string
139
+ ```
140
+
141
+ ```typescript
142
+ const fullPath = storageService.prefix('documents/report.pdf')
143
+ // → "uploads/documents/report.pdf"(假设配置了 prefix: 'uploads')
144
+ ```
145
+
146
+ ## ObjectStorageOptions
147
+
148
+ 所有方法的可选参数:
149
+
150
+ | 字段 | 类型 | 说明 |
151
+ |------|------|------|
152
+ | `prefix` | `boolean` | 是否自动拼接模块配置的 `prefix`。设为 `true` 时调用 `prefix()` 方法处理路径 |
153
+
154
+ ## 完整使用示例
155
+
156
+ ```typescript
157
+ import { Injectable } from '@nestjs/common'
158
+ import { ObjectStorageService } from '@buka/nestjs-kit'
159
+ import { Readable } from 'node:stream'
160
+
161
+ @Injectable()
162
+ export class FileService {
163
+ constructor(private readonly storage: ObjectStorageService) {}
164
+
165
+ async uploadAvatar(userId: string, file: Buffer): Promise<string> {
166
+ const path = `avatars/${userId}.png`
167
+ return this.storage.upload(path, file, { prefix: true })
168
+ }
169
+
170
+ async getAvatar(userId: string): Promise<Readable> {
171
+ const path = `avatars/${userId}.png`
172
+ return this.storage.get(path, { prefix: true })
173
+ }
174
+
175
+ async getAvatarUrl(userId: string): Promise<string> {
176
+ const path = `avatars/${userId}.png`
177
+ return this.storage.getSignedUrl(path, 3600, { prefix: true })
178
+ }
179
+
180
+ async deleteAvatar(userId: string): Promise<void> {
181
+ const path = `avatars/${userId}.png`
182
+ await this.storage.remove(path, { prefix: true })
183
+ }
184
+ }
185
+ ```
186
+
187
+ ## 注意事项
188
+
189
+ > S3 客户端在 `onModuleInit` 时初始化。确保配置的 `endpoint`、`accessKeyId` 和 `secretAccessKey` 正确,否则后续操作会失败。
190
+
191
+ > `forcePathStyle: true` 适用于 MinIO、LocalStack 等 S3 兼容服务。AWS S3 通常使用虚拟主机风格(默认 `false`)。
192
+
193
+ > `prefix` 配置会自动去除首尾斜杠后拼接。例如 prefix 为 `/uploads/` 时,`prefix('docs/a.pdf')` 返回 `uploads/docs/a.pdf`。