@buka/nestjs-kit 4.3.4 → 4.4.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.
package/dist/index.mjs CHANGED
@@ -16,7 +16,7 @@ import { Migrator } from "@mikro-orm/migrations";
16
16
  import * as fs from "node:fs";
17
17
  import { KeqRequest, RequestException } from "keq";
18
18
  import { setBaseUrl } from "@keq-request/url";
19
- import { validateStatusCode } from "@keq-request/exception";
19
+ import { createExceptionByStatusCode, validateStatusCode } from "@keq-request/exception";
20
20
  import { createCipheriv, createDecipheriv, createHash, randomBytes } from "crypto";
21
21
  import bcrypt from "bcryptjs";
22
22
  import { Base32, Base32 as Base32$1, ErrorCategory, ErrorCategory as ErrorCategory$1, ErrorCode, ErrorCode as ErrorCode$1 } from "@buka/error-codes";
@@ -2754,6 +2754,21 @@ function resolveEntityType(entityRef, eager) {
2754
2754
  if (!cls) return Object;
2755
2755
  return eager ? cls : PrimaryKeyType(cls);
2756
2756
  }
2757
+ /**
2758
+ * 为 Swagger schema 解析实体类引用。始终返回完整实体类(非 PrimaryKeyType),
2759
+ * 保证 `$ref` 指向正确注册的 schema。
2760
+ *
2761
+ * 返回函数形式以支持延迟求值,避免装饰器执行时的循环引用问题。
2762
+ */
2763
+ function resolveEntitySchemaType(entityRef) {
2764
+ return () => {
2765
+ if (!entityRef) return Object;
2766
+ const result = entityRef();
2767
+ const entityName = Array.isArray(result) ? result[0] : result;
2768
+ if (!entityName) return Object;
2769
+ return resolveEntityClass(entityName) || Object;
2770
+ };
2771
+ }
2757
2772
  //#endregion
2758
2773
  //#region src/modules/mikro-orm/decorators/cardinality/many-to-one.cardinality.ts
2759
2774
  /**
@@ -2866,8 +2881,8 @@ function OneToMany$1(options) {
2866
2881
  },
2867
2882
  schema: {
2868
2883
  description: options.comment,
2869
- type: "array",
2870
- items: { $ref: getSchemaPath(type()) }
2884
+ type: resolveEntitySchemaType(entityRef),
2885
+ isArray: true
2871
2886
  }
2872
2887
  })(target, propertyKey);
2873
2888
  };
@@ -2907,8 +2922,8 @@ function ManyToMany$1(entity, mappedBy, options) {
2907
2922
  },
2908
2923
  schema: {
2909
2924
  description: resolvedOptions?.comment,
2910
- type: "array",
2911
- items: { $ref: getSchemaPath(type()) }
2925
+ type: resolveEntitySchemaType(entityRef),
2926
+ isArray: true
2912
2927
  }
2913
2928
  })(target, propertyKey);
2914
2929
  };
@@ -9967,6 +9982,58 @@ ObjectStorageModule = __decorate([Global(), Module({
9967
9982
  exports: [ObjectStorageService]
9968
9983
  })], ObjectStorageModule);
9969
9984
  //#endregion
9970
- 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_SCALAR_DICTIONARY, IS_URN, InjectLogger, IsBrowserRequest, IsCrockfordBase32, IsDomainUrn, 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 };
9985
+ //#region src/modules/keq/buka-request.exception.ts
9986
+ var BukaRequestException = class extends RequestException {
9987
+ code;
9988
+ errorCode;
9989
+ details;
9990
+ constructor(statusCode, message, options) {
9991
+ super(statusCode, message, {
9992
+ response: options.response,
9993
+ fatal: options.fatal
9994
+ });
9995
+ this.code = options.code;
9996
+ this.errorCode = ErrorCode$1.fromString(options.code);
9997
+ this.details = options.details ?? [];
9998
+ }
9999
+ };
10000
+ //#endregion
10001
+ //#region src/modules/keq/throw-on-response-error.middleware.ts
10002
+ const logger = new Logger$1("KeqMiddleware:throwOnResponseError");
10003
+ function throwOnResponseError(options) {
10004
+ const { errorDispatchers, debug } = options ?? {};
10005
+ const middleware = async (ctx, next) => {
10006
+ await next();
10007
+ if (!ctx.response || ctx.response.status >= 200 && ctx.response.status < 400) return;
10008
+ const response = ctx.response;
10009
+ if (!response.headers.get("content-type")?.includes("application/json")) throw createExceptionByStatusCode(response);
10010
+ const body = await response.json();
10011
+ if (body !== null && typeof body === "object" && "error" in body) try {
10012
+ const { error } = body;
10013
+ const exceptionOptions = {
10014
+ code: error.code,
10015
+ details: error.details,
10016
+ response,
10017
+ fatal: [
10018
+ 401,
10019
+ 403,
10020
+ 404
10021
+ ].includes(response.status)
10022
+ };
10023
+ if (errorDispatchers && error.code in errorDispatchers) {
10024
+ const ExceptionClass = errorDispatchers[error.code];
10025
+ throw new ExceptionClass(response.status, error.message, exceptionOptions);
10026
+ }
10027
+ throw new BukaRequestException(response.status, error.message, exceptionOptions);
10028
+ } catch (caught) {
10029
+ if (debug) logger.debug("解析响应错误体失败,降级为通用异常", caught instanceof Error ? caught.stack : caught);
10030
+ }
10031
+ throw createExceptionByStatusCode(response);
10032
+ };
10033
+ middleware.__keqMiddlewareName__ = "throwOnResponseError";
10034
+ return middleware;
10035
+ }
10036
+ //#endregion
10037
+ 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_SCALAR_DICTIONARY, IS_URN, InjectLogger, IsBrowserRequest, IsCrockfordBase32, IsDomainUrn, 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 };
9971
10038
 
9972
10039
  //# sourceMappingURL=index.mjs.map