@buka/nestjs-kit 4.4.9 → 4.4.11

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
@@ -4,7 +4,7 @@ import { BigIntType, Config, Cursor, EntityManager, EntityMetadata, EntitySchema
4
4
  import { Embeddable, Embedded, Enum as Enum$1, ManyToMany, ManyToOne, OneToMany, OneToOne, PrimaryKey, Property as Property$1 } from "@mikro-orm/decorators/legacy";
5
5
  import { ArrayMinSize, IS_OPTIONAL, IsArray, IsBoolean, IsCurrency, IsDefined, IsEnum, IsISO8601, IsIn, IsInt, IsNotEmpty, IsNumber, IsNumberString, IsObject, IsOptional, IsString, IsUUID, IsUrl, MaxLength, Min, MinLength, ValidateNested, getMetadataStorage, isEnum, registerDecorator, validate, validateSync } from "class-validator";
6
6
  import { validate as validate$1 } from "jsonschema";
7
- import { ApiExtraModels, ApiHideProperty, ApiOkResponse, ApiOperation, ApiProperty, ApiPropertyOptional, ApiQuery, ApiSchema, ApiTags, OmitType as OmitType$1, PartialType as PartialType$1, PickType as PickType$1, getSchemaPath } from "@nestjs/swagger";
7
+ import { ApiExtraModels, ApiHideProperty, ApiOkResponse, ApiOperation, ApiProperty, ApiPropertyOptional, ApiQuery, ApiSchema, ApiTags, IntersectionType as IntersectionType$1, OmitType as OmitType$1, PartialType as PartialType$1, PickType as PickType$1, getSchemaPath } from "@nestjs/swagger";
8
8
  import { Transform, Type as Type$1, plainToInstance } from "class-transformer";
9
9
  import * as R from "ramda";
10
10
  import * as classTransformer from "class-transformer/cjs/storage.js";
@@ -1574,7 +1574,7 @@ function swaggerMetadataToJsonSchema(metadata) {
1574
1574
  }
1575
1575
  //#endregion
1576
1576
  //#region src/modules/core/converters/filter-query-type/get-filter-query-schema.ts
1577
- function getObjectSchema(classRef) {
1577
+ function getObjectSchema(classRef, visited = /* @__PURE__ */ new WeakSet()) {
1578
1578
  const properties = {};
1579
1579
  const requiredKeys = [];
1580
1580
  const schema = {
@@ -1582,24 +1582,28 @@ function getObjectSchema(classRef) {
1582
1582
  properties,
1583
1583
  additionalProperties: false
1584
1584
  };
1585
+ visited.add(classRef);
1585
1586
  for (const propertyKey of ModelRegister.getModelPropertyKeys(classRef)) {
1586
1587
  if (typeof propertyKey !== "string") continue;
1587
1588
  const propertyMetadata = ModelRegister.getProperty(classRef, propertyKey);
1588
1589
  const isCollection = propertyMetadata?.association?.kind === "1:m" || propertyMetadata?.association?.kind === "m:n";
1589
1590
  const isRelation = !!propertyMetadata?.association;
1590
1591
  if (!!!propertyMetadata?.optional) requiredKeys.push(propertyKey);
1591
- if (isRelation) if (isCollection) {
1592
- const sub = getObjectSchema(propertyMetadata.association.type());
1593
- const operators = getCollectionOperators(classRef, propertyKey);
1594
- const wrapper = {
1595
- type: "object",
1596
- properties: {},
1597
- additionalProperties: false
1598
- };
1599
- for (const operator of operators) wrapper.properties[operator] = sub;
1600
- properties[propertyKey] = wrapper;
1601
- } else properties[propertyKey] = getObjectSchema(propertyMetadata.association.type());
1602
- else {
1592
+ if (isRelation) {
1593
+ const relationClassRef = propertyMetadata.association.type();
1594
+ if (visited.has(relationClassRef)) continue;
1595
+ if (isCollection) {
1596
+ const sub = getObjectSchema(relationClassRef, visited);
1597
+ const operators = getCollectionOperators(classRef, propertyKey);
1598
+ const wrapper = {
1599
+ type: "object",
1600
+ properties: {},
1601
+ additionalProperties: false
1602
+ };
1603
+ for (const operator of operators) wrapper.properties[operator] = sub;
1604
+ properties[propertyKey] = wrapper;
1605
+ } else properties[propertyKey] = getObjectSchema(relationClassRef, visited);
1606
+ } else {
1603
1607
  const propertySchema = {
1604
1608
  type: "object",
1605
1609
  properties: {},
@@ -1680,41 +1684,45 @@ function createFilterQueryPropertyClassRef(classRef, propertyKey) {
1680
1684
  }
1681
1685
  return propertyClass;
1682
1686
  }
1683
- function createFilterQueryObjectClassRef(classRef) {
1687
+ function createFilterQueryObjectClassRef(classRef, visited = /* @__PURE__ */ new WeakSet()) {
1684
1688
  class FilterQueryObjectClass {}
1685
1689
  ModelRegister.addModel(FilterQueryObjectClass);
1690
+ visited.add(classRef);
1686
1691
  for (const propertyKey of ModelRegister.getModelPropertyKeys(classRef)) {
1687
1692
  if (typeof propertyKey !== "string") continue;
1688
1693
  const propertyMetadata = ModelRegister.getProperty(classRef, propertyKey);
1689
1694
  const isCollection = propertyMetadata?.association?.kind === "1:m" || propertyMetadata?.association?.kind === "m:n";
1690
1695
  const isRelation = !!propertyMetadata?.association;
1691
1696
  const isOptional = !!propertyMetadata?.optional;
1692
- if (isRelation) if (isCollection) {
1693
- class FilterQueryCollectionClass {}
1694
- ModelRegister.addModel(FilterQueryCollectionClass);
1695
- const sub = createFilterQueryObjectClassRef(propertyMetadata.association.type());
1696
- const operators = getCollectionOperators(classRef, propertyKey);
1697
- for (const operator of operators) {
1697
+ if (isRelation) {
1698
+ const relationClassRef = propertyMetadata.association.type();
1699
+ if (visited.has(relationClassRef)) continue;
1700
+ if (isCollection) {
1701
+ class FilterQueryCollectionClass {}
1702
+ ModelRegister.addModel(FilterQueryCollectionClass);
1703
+ const sub = createFilterQueryObjectClassRef(relationClassRef, visited);
1704
+ const operators = getCollectionOperators(classRef, propertyKey);
1705
+ for (const operator of operators) {
1706
+ Composite({
1707
+ type: () => sub,
1708
+ optional: true
1709
+ })(FilterQueryCollectionClass.prototype, operator);
1710
+ if (!isOptional) HasAnyKey(getFilterQueryOperators(classRef, propertyKey))(FilterQueryCollectionClass.prototype, operator);
1711
+ IsOptional()(FilterQueryCollectionClass.prototype, operator);
1712
+ }
1713
+ Composite({
1714
+ type: () => FilterQueryCollectionClass,
1715
+ optional: isOptional
1716
+ })(FilterQueryObjectClass.prototype, propertyKey);
1717
+ if (!isOptional) HasAnyKey(operators)(FilterQueryObjectClass.prototype, propertyKey);
1718
+ } else {
1719
+ const sub = createFilterQueryObjectClassRef(relationClassRef, visited);
1698
1720
  Composite({
1699
1721
  type: () => sub,
1700
- optional: true
1701
- })(FilterQueryCollectionClass.prototype, operator);
1702
- if (!isOptional) HasAnyKey(getFilterQueryOperators(classRef, propertyKey))(FilterQueryCollectionClass.prototype, operator);
1703
- IsOptional()(FilterQueryCollectionClass.prototype, operator);
1722
+ optional: isOptional
1723
+ })(FilterQueryObjectClass.prototype, propertyKey);
1704
1724
  }
1705
- Composite({
1706
- type: () => FilterQueryCollectionClass,
1707
- optional: isOptional
1708
- })(FilterQueryObjectClass.prototype, propertyKey);
1709
- if (!isOptional) HasAnyKey(operators)(FilterQueryObjectClass.prototype, propertyKey);
1710
1725
  } else {
1711
- const sub = createFilterQueryObjectClassRef(propertyMetadata.association.type());
1712
- Composite({
1713
- type: () => sub,
1714
- optional: isOptional
1715
- })(FilterQueryObjectClass.prototype, propertyKey);
1716
- }
1717
- else {
1718
1726
  const propertyClass = createFilterQueryPropertyClassRef(classRef, propertyKey);
1719
1727
  Composite({
1720
1728
  type: () => propertyClass,
@@ -2923,11 +2931,12 @@ function ManyToOne$1(entity, options) {
2923
2931
  return;
2924
2932
  }
2925
2933
  const type = () => resolveEntityType(entityRef, resolvedOptions?.eager);
2934
+ const fullEntityType = () => resolveEntityType(entityRef, true);
2926
2935
  Composite({
2927
2936
  type,
2928
2937
  association: {
2929
2938
  kind: "m:1",
2930
- type
2939
+ type: fullEntityType
2931
2940
  },
2932
2941
  schema: {
2933
2942
  description: resolvedOptions?.comment,
@@ -2961,11 +2970,12 @@ function OneToOne$1(entity, mappedByOrOptions, options) {
2961
2970
  return;
2962
2971
  }
2963
2972
  const type = () => resolveEntityType(entityRef, resolvedOptions?.eager);
2973
+ const fullEntityType = () => resolveEntityType(entityRef, true);
2964
2974
  Composite({
2965
2975
  type,
2966
2976
  association: {
2967
2977
  kind: "1:1",
2968
- type
2978
+ type: fullEntityType
2969
2979
  },
2970
2980
  schema: {
2971
2981
  description: resolvedOptions?.comment,
@@ -2999,13 +3009,14 @@ function OneToMany$1(options) {
2999
3009
  }
3000
3010
  const entityRef = options.entity;
3001
3011
  const type = () => resolveEntityType(entityRef, options.eager);
3012
+ const fullEntityType = () => resolveEntityType(entityRef, true);
3002
3013
  List({
3003
3014
  type,
3004
3015
  optional: options.nullable,
3005
3016
  lazy: options.eager !== true,
3006
3017
  association: {
3007
3018
  kind: "1:m",
3008
- type
3019
+ type: fullEntityType
3009
3020
  },
3010
3021
  schema: {
3011
3022
  description: options.comment,
@@ -3040,13 +3051,14 @@ function ManyToMany$1(entity, mappedBy, options) {
3040
3051
  return;
3041
3052
  }
3042
3053
  const type = () => resolveEntityType(entityRef, resolvedOptions?.eager);
3054
+ const fullEntityType = () => resolveEntityType(entityRef, true);
3043
3055
  List({
3044
3056
  type,
3045
3057
  optional: resolvedOptions?.nullable,
3046
3058
  lazy: resolvedOptions?.eager !== true,
3047
3059
  association: {
3048
3060
  kind: "m:n",
3049
- type
3061
+ type: fullEntityType
3050
3062
  },
3051
3063
  schema: {
3052
3064
  description: resolvedOptions?.comment,
@@ -3448,6 +3460,34 @@ function PartialType(classRef) {
3448
3460
  return PartialTypeClass;
3449
3461
  }
3450
3462
  //#endregion
3463
+ //#region src/modules/core/converters/intersection-type/intersection-type.ts
3464
+ /**
3465
+ * 将多个模型类合并为一个交叉类型。
3466
+ *
3467
+ * 类似 TypeScript 的交叉类型 `A & B`,同时合并 class-validator、class-transformer 和 Swagger 的元数据。
3468
+ *
3469
+ * @param classRefs - 需要合并的模型类引用列表
3470
+ * @returns 包含所有类属性的新类
3471
+ *
3472
+ * @example
3473
+ * ```typescript
3474
+ * const CreateUserDTO = IntersectionType(UserBaseDTO, UserProfileDTO)
3475
+ * ```
3476
+ */
3477
+ function IntersectionType(...classRefs) {
3478
+ const IntersectionTypeClass = IntersectionType$1(...classRefs);
3479
+ for (const classRef of classRefs) for (const propertyKey of ModelRegister.getModelPropertyKeys(classRef)) {
3480
+ ModelRegister.copyProperty(classRef, IntersectionTypeClass, propertyKey);
3481
+ const metadataKeys = Reflect.getMetadataKeys(classRef.prototype, propertyKey);
3482
+ for (const metadataKey of metadataKeys) {
3483
+ const metadata = Reflect.getMetadata(metadataKey, classRef.prototype, propertyKey);
3484
+ if (Reflect.hasMetadata(metadataKey, IntersectionTypeClass.prototype, propertyKey)) continue;
3485
+ Reflect.defineMetadata(metadataKey, metadata, IntersectionTypeClass.prototype, propertyKey);
3486
+ }
3487
+ }
3488
+ return IntersectionTypeClass;
3489
+ }
3490
+ //#endregion
3451
3491
  //#region src/modules/core/converters/order-query-type/get-order-query-schema.ts
3452
3492
  function getOrderQueryEnum() {
3453
3493
  return {
@@ -8409,8 +8449,14 @@ function throwOnResponseError(options) {
8409
8449
  if (!ctx.response || ctx.response.status >= 200 && ctx.response.status < 400) return;
8410
8450
  const response = ctx.response;
8411
8451
  if (!response.headers.get("content-type")?.includes("application/json")) throw createExceptionByStatusCode(response);
8412
- const body = await response.json();
8413
- if (body !== null && typeof body === "object" && "error" in body) try {
8452
+ let body;
8453
+ try {
8454
+ body = await response.json();
8455
+ } catch (err) {
8456
+ if (debug) logger.debug("响应体 JSON 解析失败,降级为状态码异常", err instanceof Error ? err.stack : err);
8457
+ throw createExceptionByStatusCode(response);
8458
+ }
8459
+ if (body !== null && typeof body === "object" && "error" in body) {
8414
8460
  const { error } = body;
8415
8461
  const exceptionOptions = {
8416
8462
  code: error.code,
@@ -8422,13 +8468,13 @@ function throwOnResponseError(options) {
8422
8468
  404
8423
8469
  ].includes(response.status)
8424
8470
  };
8425
- if (errorDispatchers && error.code in errorDispatchers) {
8471
+ if (errorDispatchers && error.code in errorDispatchers) try {
8426
8472
  const ExceptionClass = errorDispatchers[error.code];
8427
8473
  throw new ExceptionClass(response.status, error.message, exceptionOptions);
8474
+ } catch (caught) {
8475
+ if (debug) logger.debug("自定义异常派发失败,降级为 BukaRequestException", caught instanceof Error ? caught.stack : caught);
8428
8476
  }
8429
8477
  throw new BukaRequestException(response.status, error.message, exceptionOptions);
8430
- } catch (caught) {
8431
- if (debug) logger.debug("解析响应错误体失败,降级为通用异常", caught instanceof Error ? caught.stack : caught);
8432
8478
  }
8433
8479
  throw createExceptionByStatusCode(response);
8434
8480
  };
@@ -8436,6 +8482,6 @@ function throwOnResponseError(options) {
8436
8482
  return middleware;
8437
8483
  }
8438
8484
  //#endregion
8439
- export { AuthException, BUKA_MODULE_OPTIONS_TOKEN, Base32, BlindIndex, BlindIndexModule, BlindIndexService, BlindIndexV1Hasher, BukaConfigurableModuleClass, BukaExceptions, BukaModule, BukaPageQueryValidationPipe, BukaRequestException, 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_ENUM_COLUMN, IS_SCALAR_DICTIONARY, IS_URN, InjectLogger, IsBrowserRequest, IsCrockfordBase32, IsDomainUrn, IsEnumColumn, 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, throwOnResponseError };
8485
+ export { AuthException, BUKA_MODULE_OPTIONS_TOKEN, Base32, BlindIndex, BlindIndexModule, BlindIndexService, BlindIndexV1Hasher, BukaConfigurableModuleClass, BukaExceptions, BukaModule, BukaPageQueryValidationPipe, BukaRequestException, 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_ENUM_COLUMN, IS_SCALAR_DICTIONARY, IS_URN, InjectLogger, IntersectionType, IsBrowserRequest, IsCrockfordBase32, IsDomainUrn, IsEnumColumn, 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, throwOnResponseError };
8440
8486
 
8441
8487
  //# sourceMappingURL=index.mjs.map