@buka/nestjs-kit 4.3.1 → 4.3.3

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.
package/dist/index.mjs CHANGED
@@ -966,7 +966,7 @@ function Composite(options) {
966
966
  if (optional) IsOptional()(target, propertyKey);
967
967
  else IsNotEmpty({ message: "$property is required" })(target, propertyKey);
968
968
  Type$1(options.type)(target, propertyKey);
969
- if (optional) ApiPropertyOptional(schema)(target, propertyKey);
969
+ if (!options.lazy) if (optional) ApiPropertyOptional(schema)(target, propertyKey);
970
970
  else ApiProperty(schema)(target, propertyKey);
971
971
  ModelRegister.addProperty(target.constructor, propertyKey, {
972
972
  kind: "composite",
@@ -991,7 +991,7 @@ function applyUntypedList(target, propertyKey, options) {
991
991
  each: true,
992
992
  message: "$property is required"
993
993
  })(target, propertyKey);
994
- if (optional) ApiPropertyOptional(schema)(target, propertyKey);
994
+ if (!options.lazy) if (optional) ApiPropertyOptional(schema)(target, propertyKey);
995
995
  else ApiProperty(schema)(target, propertyKey);
996
996
  ModelRegister.addProperty(target.constructor, propertyKey, {
997
997
  kind: "list",
@@ -1015,7 +1015,7 @@ function applyScalarList(target, propertyKey, options) {
1015
1015
  each: true,
1016
1016
  message: "$property is required"
1017
1017
  })(target, propertyKey);
1018
- if (optional) ApiPropertyOptional(schema)(target, propertyKey);
1018
+ if (!options.lazy) if (optional) ApiPropertyOptional(schema)(target, propertyKey);
1019
1019
  else ApiProperty(schema)(target, propertyKey);
1020
1020
  ModelRegister.addProperty(target.constructor, propertyKey, {
1021
1021
  kind: "list",
@@ -1040,7 +1040,7 @@ function applyCompositeList(target, propertyKey, options) {
1040
1040
  each: true,
1041
1041
  message: "$property is required"
1042
1042
  })(target, propertyKey);
1043
- if (optional) ApiPropertyOptional(schema)(target, propertyKey);
1043
+ if (!options.lazy) if (optional) ApiPropertyOptional(schema)(target, propertyKey);
1044
1044
  else ApiProperty(schema)(target, propertyKey);
1045
1045
  ModelRegister.addProperty(target.constructor, propertyKey, {
1046
1046
  kind: "list",
@@ -2756,6 +2756,48 @@ __decorate([
2756
2756
  __decorateMetadata("design:type", String)
2757
2757
  ], DiscreteEntity.prototype, "id", void 0);
2758
2758
  //#endregion
2759
+ //#region src/modules/mikro-orm/converters/entity-dto-type/entity-dto-type.ts
2760
+ /**
2761
+ * 基于实体生成一个无继承关系的纯 DTO 类,用于安全派生。
2762
+ *
2763
+ * 返回的类:
2764
+ * - 不继承实体类,避免 `Collection` 类型与 DTO 字段冲突
2765
+ * - 仅包含非 `lazy: true` 的 Model 属性
2766
+ * - 保留 `Ref<Entity>` 类型(序列化层自动处理:populated 时完整序列化,否则仅主键)
2767
+ * - 保留所有 Swagger、class-validator、class-transformer 元数据
2768
+ * - Swagger schema 与 `findOne()` 不加 populate 的结果一致
2769
+ *
2770
+ * @param classRef - 使用 `@Model()` 标注的实体类引用
2771
+ * @returns 可用于 `extends` 派生的纯 DTO 类
2772
+ *
2773
+ * @example
2774
+ * ```typescript
2775
+ * // 基本用法:派生不含 Collection 的 DTO
2776
+ * class UserProfileBriefDto extends EntityDto(UserProfile) {}
2777
+ *
2778
+ * // 扩展用法:手动添加 lazy 属性
2779
+ * class UserProfileDetailDto extends EntityDto(UserProfile) {
2780
+ * @List({ type: () => PrimaryKeyType(Avatar) })
2781
+ * avatars!: PrimaryKeyTypeClass[]
2782
+ * }
2783
+ * ```
2784
+ */
2785
+ function EntityDto(classRef) {
2786
+ if (!ModelRegister.isModel(classRef)) throw new TypeError("EntityDto only accepts a class annotated with @Model().");
2787
+ class EntityDtoClass {}
2788
+ for (const propertyKey of ModelRegister.getModelPropertyKeys(classRef)) {
2789
+ if (ModelRegister.getProperty(classRef, propertyKey)?.lazy) continue;
2790
+ ModelRegister.copyProperty(classRef, EntityDtoClass, propertyKey);
2791
+ const metadataKeys = Reflect.getMetadataKeys(classRef.prototype, propertyKey);
2792
+ for (const metadataKey of metadataKeys) {
2793
+ const value = Reflect.getMetadata(metadataKey, classRef.prototype, propertyKey);
2794
+ if (Reflect.hasMetadata(metadataKey, EntityDtoClass.prototype, propertyKey)) continue;
2795
+ Reflect.defineMetadata(metadataKey, value, EntityDtoClass.prototype, propertyKey);
2796
+ }
2797
+ }
2798
+ return EntityDtoClass;
2799
+ }
2800
+ //#endregion
2759
2801
  //#region src/modules/mikro-orm/utils/mikro-orm-utils.ts
2760
2802
  function getMetadata(classRef) {
2761
2803
  const metadatas = [];
@@ -2916,6 +2958,7 @@ function OneToMany$1(options) {
2916
2958
  List({
2917
2959
  type,
2918
2960
  optional: options.nullable,
2961
+ lazy: options.eager !== true,
2919
2962
  association: {
2920
2963
  kind: "1:m",
2921
2964
  type
@@ -2956,6 +2999,7 @@ function ManyToMany$1(entity, mappedBy, options) {
2956
2999
  List({
2957
3000
  type,
2958
3001
  optional: resolvedOptions?.nullable,
3002
+ lazy: resolvedOptions?.eager !== true,
2959
3003
  association: {
2960
3004
  kind: "m:n",
2961
3005
  type
@@ -3265,6 +3309,36 @@ var Slice = class Slice {
3265
3309
  }
3266
3310
  };
3267
3311
  //#endregion
3312
+ //#region src/modules/core/converters/pick-type/pick-type.ts
3313
+ /**
3314
+ * 从模型中选取指定属性,生成新的子集类型。
3315
+ *
3316
+ * 类似 TypeScript 的 `Pick<T, K>`,同时保留 class-validator、class-transformer 和 Swagger 的元数据。
3317
+ *
3318
+ * @param classRef - 使用 `@Model()` 标注的类引用
3319
+ * @param keys - 需要选取的属性名数组
3320
+ * @returns 仅包含指定属性的新类
3321
+ *
3322
+ * @example
3323
+ * ```typescript
3324
+ * const CreateUserDTO = PickType(UserDTO, ['name', 'email'])
3325
+ * ```
3326
+ */
3327
+ function PickType(classRef, keys) {
3328
+ if (!ModelRegister.isModel(classRef)) throw new TypeError("PickType only accepts a class annotated with @Model().");
3329
+ const PickTypeClass = PickType$1(classRef, keys);
3330
+ for (const key of keys) {
3331
+ ModelRegister.copyProperty(classRef, PickTypeClass, key);
3332
+ const metadataKeys = Reflect.getMetadataKeys(classRef.prototype, key);
3333
+ for (const metadataKey of metadataKeys) {
3334
+ const metadata = Reflect.getMetadata(metadataKey, classRef.prototype, key);
3335
+ if (Reflect.hasMetadata(metadataKey, PickTypeClass.prototype, key)) continue;
3336
+ Reflect.defineMetadata(metadataKey, metadata, PickTypeClass.prototype, key);
3337
+ }
3338
+ }
3339
+ return PickTypeClass;
3340
+ }
3341
+ //#endregion
3268
3342
  //#region src/modules/core/converters/omit-type/omit-type.ts
3269
3343
  /**
3270
3344
  * 从模型中排除指定属性,生成新的类型。
@@ -3296,68 +3370,6 @@ function OmitType(classRef, keys) {
3296
3370
  return OmitTypeClass;
3297
3371
  }
3298
3372
  //#endregion
3299
- //#region src/modules/core/converters/eager-type/eager-type.ts
3300
- /**
3301
- * 从模型中排除所有标记为 `lazy: true` 的属性,生成仅包含非懒加载字段的新类型。
3302
- *
3303
- * 适用于 API 响应场景,避免返回未加载的字段。
3304
- *
3305
- * @param classRef - 使用 `@Model()` 标注的类引用
3306
- * @returns 排除了 lazy 属性的新类
3307
- *
3308
- * @example
3309
- * ```typescript
3310
- * @Model()
3311
- * class User {
3312
- * @Property()
3313
- * name: string
3314
- *
3315
- * @Property({ lazy: true })
3316
- * bio: string
3317
- * }
3318
- *
3319
- * const UserResponse = EagerType(User)
3320
- * // UserResponse 仅包含 name,不包含 bio
3321
- * ```
3322
- */
3323
- function EagerType(classRef) {
3324
- if (!ModelRegister.isModel(classRef)) throw new TypeError("EagerType only accepts a class annotated with @Model().");
3325
- const lazyKeys = [];
3326
- for (const propertyKey of ModelRegister.getModelPropertyKeys(classRef)) if (ModelRegister.getProperty(classRef, propertyKey)?.lazy) lazyKeys.push(propertyKey);
3327
- if (lazyKeys.length === 0) return classRef;
3328
- return OmitType(classRef, lazyKeys);
3329
- }
3330
- //#endregion
3331
- //#region src/modules/core/converters/pick-type/pick-type.ts
3332
- /**
3333
- * 从模型中选取指定属性,生成新的子集类型。
3334
- *
3335
- * 类似 TypeScript 的 `Pick<T, K>`,同时保留 class-validator、class-transformer 和 Swagger 的元数据。
3336
- *
3337
- * @param classRef - 使用 `@Model()` 标注的类引用
3338
- * @param keys - 需要选取的属性名数组
3339
- * @returns 仅包含指定属性的新类
3340
- *
3341
- * @example
3342
- * ```typescript
3343
- * const CreateUserDTO = PickType(UserDTO, ['name', 'email'])
3344
- * ```
3345
- */
3346
- function PickType(classRef, keys) {
3347
- if (!ModelRegister.isModel(classRef)) throw new TypeError("PickType only accepts a class annotated with @Model().");
3348
- const PickTypeClass = PickType$1(classRef, keys);
3349
- for (const key of keys) {
3350
- ModelRegister.copyProperty(classRef, PickTypeClass, key);
3351
- const metadataKeys = Reflect.getMetadataKeys(classRef.prototype, key);
3352
- for (const metadataKey of metadataKeys) {
3353
- const metadata = Reflect.getMetadata(metadataKey, classRef.prototype, key);
3354
- if (Reflect.hasMetadata(metadataKey, PickTypeClass.prototype, key)) continue;
3355
- Reflect.defineMetadata(metadataKey, metadata, PickTypeClass.prototype, key);
3356
- }
3357
- }
3358
- return PickTypeClass;
3359
- }
3360
- //#endregion
3361
3373
  //#region src/modules/core/converters/partial-type/partial-type.ts
3362
3374
  /**
3363
3375
  * 将模型的所有属性变为可选,生成新的 Partial 类型。
@@ -3709,12 +3721,12 @@ let OpenBaoTokenManager = _OpenBaoTokenManager = class OpenBaoTokenManager {
3709
3721
  this.logger.log("Token renewed successfully");
3710
3722
  this.scheduleRenewal();
3711
3723
  } catch (renewError) {
3712
- this.logger.error("Failed to renew token, attempting re-authentication", renewError);
3724
+ this.logger.error("Failed to renew token, attempting re-authentication", renewError instanceof Error ? renewError.stack : void 0);
3713
3725
  try {
3714
3726
  await this.authenticate();
3715
3727
  this.scheduleRenewal();
3716
3728
  } catch (authError) {
3717
- this.logger.error("Re-authentication also failed, will retry in 5s", authError);
3729
+ this.logger.error("Re-authentication also failed, will retry in 5s", authError instanceof Error ? authError.stack : void 0);
3718
3730
  this.renewalTimer = setTimeout(() => {
3719
3731
  this.renewToken();
3720
3732
  }, 5e3);
@@ -9928,13 +9940,19 @@ let ObjectStorageService = _ObjectStorageService = class ObjectStorageService {
9928
9940
  * @param options - 可选配置,如是否自动添加前缀
9929
9941
  */
9930
9942
  async get(path, options) {
9943
+ const key = this.buildPath(path, options);
9931
9944
  const command = new GetObjectCommand({
9932
9945
  Bucket: this.config.bucket,
9933
- Key: this.buildPath(path, options)
9946
+ Key: key
9934
9947
  });
9935
- const res = await this.client.send(command);
9936
- if (!res.Body) throw new Error("No body");
9937
- return Readable.fromWeb(res.Body.transformToWebStream());
9948
+ try {
9949
+ const res = await this.client.send(command);
9950
+ if (!res.Body) throw new Error("No body");
9951
+ return Readable.fromWeb(res.Body.transformToWebStream());
9952
+ } catch (err) {
9953
+ this.logger.error(`对象存储下载失败, bucket: ${this.config.bucket}, key: ${key}`, err instanceof Error ? err.stack : void 0);
9954
+ throw err;
9955
+ }
9938
9956
  }
9939
9957
  /**
9940
9958
  * 上传文件内容到指定路径。
@@ -9946,41 +9964,55 @@ let ObjectStorageService = _ObjectStorageService = class ObjectStorageService {
9946
9964
  */
9947
9965
  async upload(path, contents, options) {
9948
9966
  const key = this.buildPath(path, options);
9949
- await new Upload({
9967
+ const upload = new Upload({
9950
9968
  client: this.client,
9951
9969
  params: {
9952
9970
  Bucket: this.config.bucket,
9953
9971
  Key: key,
9954
9972
  Body: contents
9955
9973
  }
9956
- }).done();
9957
- return key;
9974
+ });
9975
+ try {
9976
+ await upload.done();
9977
+ return key;
9978
+ } catch (err) {
9979
+ this.logger.error(`对象存储上传失败, bucket: ${this.config.bucket}, key: ${key}`, err instanceof Error ? err.stack : void 0);
9980
+ throw err;
9981
+ }
9958
9982
  }
9959
9983
  /**
9960
9984
  * 获取文件的元数据(metadata)。
9961
9985
  */
9962
9986
  async getMetadata(path, options) {
9987
+ const key = this.buildPath(path, options);
9963
9988
  const command = new HeadObjectCommand({
9964
9989
  Bucket: this.config.bucket,
9965
- Key: this.buildPath(path, options)
9990
+ Key: key
9966
9991
  });
9967
- const res = await this.client.send(command);
9968
- if (!res.Metadata) throw new Error("No metadata");
9969
- return res.Metadata;
9992
+ try {
9993
+ const res = await this.client.send(command);
9994
+ if (!res.Metadata) throw new Error("No metadata");
9995
+ return res.Metadata;
9996
+ } catch (err) {
9997
+ this.logger.error(`对象存储获取元数据失败, bucket: ${this.config.bucket}, key: ${key}`, err instanceof Error ? err.stack : void 0);
9998
+ throw err;
9999
+ }
9970
10000
  }
9971
10001
  /**
9972
10002
  * 检查文件是否存在。
9973
10003
  */
9974
10004
  async exists(path, options) {
10005
+ const key = this.buildPath(path, options);
9975
10006
  const command = new HeadObjectCommand({
9976
10007
  Bucket: this.config.bucket,
9977
- Key: this.buildPath(path, options)
10008
+ Key: key
9978
10009
  });
9979
10010
  try {
9980
10011
  await this.client.send(command);
9981
10012
  return true;
9982
10013
  } catch (err) {
9983
10014
  if (err instanceof Error && err.name === "NotFound") return false;
10015
+ this.logger.error(`对象存储检查文件存在性失败, bucket: ${this.config.bucket}, key: ${key}`, err instanceof Error ? err.stack : void 0);
9984
10016
  throw err;
9985
10017
  }
9986
10018
  }
@@ -9988,11 +10020,17 @@ let ObjectStorageService = _ObjectStorageService = class ObjectStorageService {
9988
10020
  * 删除指定路径的文件。
9989
10021
  */
9990
10022
  async remove(path, options) {
10023
+ const key = this.buildPath(path, options);
9991
10024
  const command = new DeleteObjectCommand({
9992
10025
  Bucket: this.config.bucket,
9993
- Key: this.buildPath(path, options)
10026
+ Key: key
9994
10027
  });
9995
- await this.client.send(command);
10028
+ try {
10029
+ await this.client.send(command);
10030
+ } catch (err) {
10031
+ this.logger.error(`对象存储删除文件失败, bucket: ${this.config.bucket}, key: ${key}`, err instanceof Error ? err.stack : void 0);
10032
+ throw err;
10033
+ }
9996
10034
  }
9997
10035
  /**
9998
10036
  * 获取文件的预签名 URL,用于临时授权访问。
@@ -10002,11 +10040,17 @@ let ObjectStorageService = _ObjectStorageService = class ObjectStorageService {
10002
10040
  * @param options - 可选配置
10003
10041
  */
10004
10042
  async getSignedUrl(path, expiresInSecond, options) {
10043
+ const key = this.buildPath(path, options);
10005
10044
  const command = new GetObjectCommand({
10006
10045
  Bucket: this.config.bucket,
10007
- Key: this.buildPath(path, options)
10046
+ Key: key
10008
10047
  });
10009
- return await getSignedUrl(this.client, command, { expiresIn: expiresInSecond });
10048
+ try {
10049
+ return await getSignedUrl(this.client, command, { expiresIn: expiresInSecond });
10050
+ } catch (err) {
10051
+ this.logger.error(`对象存储获取签名URL失败, bucket: ${this.config.bucket}, key: ${key}`, err instanceof Error ? err.stack : void 0);
10052
+ throw err;
10053
+ }
10010
10054
  }
10011
10055
  };
10012
10056
  ObjectStorageService = _ObjectStorageService = __decorate([
@@ -10022,6 +10066,6 @@ ObjectStorageModule = __decorate([Global(), Module({
10022
10066
  exports: [ObjectStorageService]
10023
10067
  })], ObjectStorageModule);
10024
10068
  //#endregion
10025
- export { AuthException, BUKA_MODULE_OPTIONS_TOKEN, Base32, BlindIndex, BlindIndexModule, BlindIndexService, BlindIndexV1Hasher, BukaConfigurableModuleClass, BukaExceptions, BukaModule, BukaPageQueryValidationPipe, BukaValidationPipe, BusinessException, Cardinality, Column, Composite, ConfigurableModuleClass, ConflictException, CursorPagination, DatabaseConfig, DegradeException, Dictionary, DiscreteEntity, EagerType, EncryptedPayload, EntityRef, Enum, EnvelopeEncryptionModule, EnvelopeEncryptionService, ErrorCategory, ErrorCode, ErrorCodeController, ErrorCodeExceptionFilter, ErrorCodeDefinitionDto as ErrorCodeItemDto, ErrorCodeMetadataDto, ErrorCodePartsDto, ErrorCodeRegistry, ErrorResponseSchema, ExceptionDetailSchema, ExceptionModule, FeatureException, FilterQuery, FilterQueryOperators, FilterQueryOperatorsMetadataKey, FilterQueryTransformPipe, HAS_ANY_KEY, HasAnyKey, HttpException, IS_CROCKFORD_BASE32, IS_DOMAIN_URN, IS_RESOURCE_ID_URN, IS_RESOURCE_TYPE_URN, IS_SCALAR_DICTIONARY, IS_URN, InjectLogger, IsBrowserRequest, IsCrockfordBase32, IsDomainUrn, IsResourceIdUrn, IsResourceTypeUrn, IsScalar, IsScalarDictionary, IsUrn, KeyEnvelope, LinearEntity, List, ListErrorCodesResponseDto, ListResponseBodyType, Logger, LoggerConfig, LoggerErrorInterceptor, LoggerModule, MATCH_JSON_SCHEMA, MODULE_OPTIONS_TOKEN, MatchJsonSchema, MatchesUrn, Model, ModelRegister, ModuleExceptions, NextCursorPageSchema, ObjectStorageModule, ObjectStorageModuleConfig, ObjectStorageService, OffsetPageSchema, OffsetPagination, OmitType, OpenBaoAppRoleAuthConfig, OpenBaoHttpClient, OpenBaoKubernetesAuthConfig, OpenBaoModule, OpenBaoModuleConfig, OpenBaoTokenAuthConfig, OpenBaoTokenManager, OpenBaoUserpassAuthConfig, OptionalPageQuery, OrderQueryType, PageQuery, ParseUUIDv7Pipe, PartialType, PendingException, PickType, PreviousCursorPageSchema, PrimaryKeyType, PrimaryKeyTypeClassMetadataPropertyKey, Property, RateLimitException, ResponseBodyType, SaltedHash, SaltedHashModule, SaltedHashService, SaltedHashV1Hasher, Slice, SwaggerPatcher, SystemException, ThirdPartyException, TimestampedEntity, Urn, VALIDATE_NESTED_DICTIONARY, ValidateNestedDictionary, ValidationException, getExceptionModuleId, getFilterQueryOperators, isScalarClass, serializeModel, setOpenBaoToken, stableStringify };
10069
+ export { AuthException, BUKA_MODULE_OPTIONS_TOKEN, Base32, BlindIndex, BlindIndexModule, BlindIndexService, BlindIndexV1Hasher, BukaConfigurableModuleClass, BukaExceptions, BukaModule, BukaPageQueryValidationPipe, BukaValidationPipe, BusinessException, Cardinality, Column, Composite, ConfigurableModuleClass, ConflictException, CursorPagination, DatabaseConfig, DegradeException, Dictionary, DiscreteEntity, EncryptedPayload, EntityDto, EntityRef, Enum, EnvelopeEncryptionModule, EnvelopeEncryptionService, ErrorCategory, ErrorCode, ErrorCodeController, ErrorCodeExceptionFilter, ErrorCodeDefinitionDto as ErrorCodeItemDto, ErrorCodeMetadataDto, ErrorCodePartsDto, ErrorCodeRegistry, ErrorResponseSchema, ExceptionDetailSchema, ExceptionModule, FeatureException, FilterQuery, FilterQueryOperators, FilterQueryOperatorsMetadataKey, FilterQueryTransformPipe, HAS_ANY_KEY, HasAnyKey, HttpException, IS_CROCKFORD_BASE32, IS_DOMAIN_URN, IS_RESOURCE_ID_URN, IS_RESOURCE_TYPE_URN, IS_SCALAR_DICTIONARY, IS_URN, InjectLogger, IsBrowserRequest, IsCrockfordBase32, IsDomainUrn, IsResourceIdUrn, IsResourceTypeUrn, IsScalar, IsScalarDictionary, IsUrn, KeyEnvelope, LinearEntity, List, ListErrorCodesResponseDto, ListResponseBodyType, Logger, LoggerConfig, LoggerErrorInterceptor, LoggerModule, MATCH_JSON_SCHEMA, MODULE_OPTIONS_TOKEN, MatchJsonSchema, MatchesUrn, Model, ModelRegister, ModuleExceptions, NextCursorPageSchema, ObjectStorageModule, ObjectStorageModuleConfig, ObjectStorageService, OffsetPageSchema, OffsetPagination, OmitType, OpenBaoAppRoleAuthConfig, OpenBaoHttpClient, OpenBaoKubernetesAuthConfig, OpenBaoModule, OpenBaoModuleConfig, OpenBaoTokenAuthConfig, OpenBaoTokenManager, OpenBaoUserpassAuthConfig, OptionalPageQuery, OrderQueryType, PageQuery, ParseUUIDv7Pipe, PartialType, PendingException, PickType, PreviousCursorPageSchema, PrimaryKeyType, PrimaryKeyTypeClassMetadataPropertyKey, Property, RateLimitException, ResponseBodyType, SaltedHash, SaltedHashModule, SaltedHashService, SaltedHashV1Hasher, Slice, SwaggerPatcher, SystemException, ThirdPartyException, TimestampedEntity, Urn, VALIDATE_NESTED_DICTIONARY, ValidateNestedDictionary, ValidationException, getExceptionModuleId, getFilterQueryOperators, isScalarClass, serializeModel, setOpenBaoToken, stableStringify };
10026
10070
 
10027
10071
  //# sourceMappingURL=index.mjs.map