@dangao/bun-server 1.2.0 → 1.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.
Files changed (162) hide show
  1. package/README.md +15 -0
  2. package/dist/config/config-module.d.ts +17 -0
  3. package/dist/config/config-module.d.ts.map +1 -1
  4. package/dist/config/service.d.ts +18 -1
  5. package/dist/config/service.d.ts.map +1 -1
  6. package/dist/config/types.d.ts +25 -0
  7. package/dist/config/types.d.ts.map +1 -1
  8. package/dist/controller/controller.d.ts +5 -0
  9. package/dist/controller/controller.d.ts.map +1 -1
  10. package/dist/controller/decorators.d.ts +30 -1
  11. package/dist/controller/decorators.d.ts.map +1 -1
  12. package/dist/controller/index.d.ts +2 -2
  13. package/dist/controller/index.d.ts.map +1 -1
  14. package/dist/controller/param-binder.d.ts +12 -0
  15. package/dist/controller/param-binder.d.ts.map +1 -1
  16. package/dist/core/application.d.ts +15 -0
  17. package/dist/core/application.d.ts.map +1 -1
  18. package/dist/core/context.d.ts +1 -0
  19. package/dist/core/context.d.ts.map +1 -1
  20. package/dist/core/server.d.ts +8 -0
  21. package/dist/core/server.d.ts.map +1 -1
  22. package/dist/index.d.ts +8 -2
  23. package/dist/index.d.ts.map +1 -1
  24. package/dist/index.js +6487 -4178
  25. package/dist/microservice/config-center/config-center-module.d.ts +43 -0
  26. package/dist/microservice/config-center/config-center-module.d.ts.map +1 -0
  27. package/dist/microservice/config-center/decorators.d.ts +58 -0
  28. package/dist/microservice/config-center/decorators.d.ts.map +1 -0
  29. package/dist/microservice/config-center/index.d.ts +9 -0
  30. package/dist/microservice/config-center/index.d.ts.map +1 -0
  31. package/dist/microservice/config-center/nacos-config-center.d.ts +37 -0
  32. package/dist/microservice/config-center/nacos-config-center.d.ts.map +1 -0
  33. package/dist/microservice/config-center/nacos-decorators.d.ts +24 -0
  34. package/dist/microservice/config-center/nacos-decorators.d.ts.map +1 -0
  35. package/dist/microservice/config-center/types.d.ts +63 -0
  36. package/dist/microservice/config-center/types.d.ts.map +1 -0
  37. package/dist/microservice/governance/circuit-breaker.d.ts +54 -0
  38. package/dist/microservice/governance/circuit-breaker.d.ts.map +1 -0
  39. package/dist/microservice/governance/decorators.d.ts +51 -0
  40. package/dist/microservice/governance/decorators.d.ts.map +1 -0
  41. package/dist/microservice/governance/index.d.ts +9 -0
  42. package/dist/microservice/governance/index.d.ts.map +1 -0
  43. package/dist/microservice/governance/rate-limiter.d.ts +26 -0
  44. package/dist/microservice/governance/rate-limiter.d.ts.map +1 -0
  45. package/dist/microservice/governance/redis-rate-limiter.d.ts +76 -0
  46. package/dist/microservice/governance/redis-rate-limiter.d.ts.map +1 -0
  47. package/dist/microservice/governance/retry-strategy.d.ts +21 -0
  48. package/dist/microservice/governance/retry-strategy.d.ts.map +1 -0
  49. package/dist/microservice/governance/types.d.ts +212 -0
  50. package/dist/microservice/governance/types.d.ts.map +1 -0
  51. package/dist/microservice/index.d.ts +10 -0
  52. package/dist/microservice/index.d.ts.map +1 -0
  53. package/dist/microservice/monitoring/index.d.ts +4 -0
  54. package/dist/microservice/monitoring/index.d.ts.map +1 -0
  55. package/dist/microservice/monitoring/metrics-collector.d.ts +54 -0
  56. package/dist/microservice/monitoring/metrics-collector.d.ts.map +1 -0
  57. package/dist/microservice/monitoring/metrics-integration.d.ts +24 -0
  58. package/dist/microservice/monitoring/metrics-integration.d.ts.map +1 -0
  59. package/dist/microservice/monitoring/types.d.ts +99 -0
  60. package/dist/microservice/monitoring/types.d.ts.map +1 -0
  61. package/dist/microservice/service-client/call-decorators.d.ts +52 -0
  62. package/dist/microservice/service-client/call-decorators.d.ts.map +1 -0
  63. package/dist/microservice/service-client/decorators.d.ts +35 -0
  64. package/dist/microservice/service-client/decorators.d.ts.map +1 -0
  65. package/dist/microservice/service-client/index.d.ts +7 -0
  66. package/dist/microservice/service-client/index.d.ts.map +1 -0
  67. package/dist/microservice/service-client/interceptors.d.ts +96 -0
  68. package/dist/microservice/service-client/interceptors.d.ts.map +1 -0
  69. package/dist/microservice/service-client/load-balancer.d.ts +59 -0
  70. package/dist/microservice/service-client/load-balancer.d.ts.map +1 -0
  71. package/dist/microservice/service-client/service-client.d.ts +74 -0
  72. package/dist/microservice/service-client/service-client.d.ts.map +1 -0
  73. package/dist/microservice/service-client/types.d.ts +155 -0
  74. package/dist/microservice/service-client/types.d.ts.map +1 -0
  75. package/dist/microservice/service-registry/decorators.d.ts +84 -0
  76. package/dist/microservice/service-registry/decorators.d.ts.map +1 -0
  77. package/dist/microservice/service-registry/discovery-decorators.d.ts +58 -0
  78. package/dist/microservice/service-registry/discovery-decorators.d.ts.map +1 -0
  79. package/dist/microservice/service-registry/health-integration.d.ts +32 -0
  80. package/dist/microservice/service-registry/health-integration.d.ts.map +1 -0
  81. package/dist/microservice/service-registry/index.d.ts +10 -0
  82. package/dist/microservice/service-registry/index.d.ts.map +1 -0
  83. package/dist/microservice/service-registry/nacos-service-registry.d.ts +68 -0
  84. package/dist/microservice/service-registry/nacos-service-registry.d.ts.map +1 -0
  85. package/dist/microservice/service-registry/service-registry-module.d.ts +48 -0
  86. package/dist/microservice/service-registry/service-registry-module.d.ts.map +1 -0
  87. package/dist/microservice/service-registry/types.d.ts +121 -0
  88. package/dist/microservice/service-registry/types.d.ts.map +1 -0
  89. package/dist/microservice/tracing/collectors.d.ts +27 -0
  90. package/dist/microservice/tracing/collectors.d.ts.map +1 -0
  91. package/dist/microservice/tracing/index.d.ts +4 -0
  92. package/dist/microservice/tracing/index.d.ts.map +1 -0
  93. package/dist/microservice/tracing/tracer.d.ts +59 -0
  94. package/dist/microservice/tracing/tracer.d.ts.map +1 -0
  95. package/dist/microservice/tracing/types.d.ts +179 -0
  96. package/dist/microservice/tracing/types.d.ts.map +1 -0
  97. package/dist/request/request.d.ts +1 -0
  98. package/dist/request/request.d.ts.map +1 -1
  99. package/docs/microservice-config-center.md +258 -0
  100. package/docs/microservice-nacos.md +346 -0
  101. package/docs/microservice-service-registry.md +306 -0
  102. package/docs/microservice.md +680 -0
  103. package/docs/troubleshooting.md +41 -0
  104. package/docs/zh/troubleshooting.md +41 -0
  105. package/package.json +5 -4
  106. package/src/config/config-module.ts +210 -0
  107. package/src/config/service.ts +52 -1
  108. package/src/config/types.ts +31 -0
  109. package/src/controller/controller.ts +8 -0
  110. package/src/controller/decorators.ts +55 -0
  111. package/src/controller/index.ts +16 -2
  112. package/src/controller/param-binder.ts +87 -1
  113. package/src/core/application.ts +100 -2
  114. package/src/core/context.ts +1 -0
  115. package/src/core/server.ts +14 -0
  116. package/src/index.ts +98 -2
  117. package/src/microservice/config-center/config-center-module.ts +98 -0
  118. package/src/microservice/config-center/decorators.ts +159 -0
  119. package/src/microservice/config-center/index.ts +13 -0
  120. package/src/microservice/config-center/nacos-config-center.ts +126 -0
  121. package/src/microservice/config-center/nacos-decorators.ts +34 -0
  122. package/src/microservice/config-center/types.ts +80 -0
  123. package/src/microservice/governance/circuit-breaker.ts +229 -0
  124. package/src/microservice/governance/decorators.ts +113 -0
  125. package/src/microservice/governance/index.ts +18 -0
  126. package/src/microservice/governance/rate-limiter.ts +72 -0
  127. package/src/microservice/governance/redis-rate-limiter.ts +154 -0
  128. package/src/microservice/governance/retry-strategy.ts +74 -0
  129. package/src/microservice/governance/types.ts +247 -0
  130. package/src/microservice/index.ts +12 -0
  131. package/src/microservice/monitoring/index.ts +8 -0
  132. package/src/microservice/monitoring/metrics-collector.ts +223 -0
  133. package/src/microservice/monitoring/metrics-integration.ts +154 -0
  134. package/src/microservice/monitoring/types.ts +118 -0
  135. package/src/microservice/service-client/call-decorators.ts +107 -0
  136. package/src/microservice/service-client/decorators.ts +87 -0
  137. package/src/microservice/service-client/index.ts +37 -0
  138. package/src/microservice/service-client/interceptors.ts +182 -0
  139. package/src/microservice/service-client/load-balancer.ts +205 -0
  140. package/src/microservice/service-client/service-client.ts +488 -0
  141. package/src/microservice/service-client/types.ts +186 -0
  142. package/src/microservice/service-registry/decorators.ts +238 -0
  143. package/src/microservice/service-registry/discovery-decorators.ts +156 -0
  144. package/src/microservice/service-registry/health-integration.ts +146 -0
  145. package/src/microservice/service-registry/index.ts +20 -0
  146. package/src/microservice/service-registry/nacos-service-registry.ts +259 -0
  147. package/src/microservice/service-registry/service-registry-module.ts +105 -0
  148. package/src/microservice/service-registry/types.ts +149 -0
  149. package/src/microservice/tracing/collectors.ts +50 -0
  150. package/src/microservice/tracing/index.ts +15 -0
  151. package/src/microservice/tracing/tracer.ts +293 -0
  152. package/src/microservice/tracing/types.ts +213 -0
  153. package/src/request/request.ts +1 -0
  154. package/tests/config/set-value-by-path.test.ts +53 -0
  155. package/tests/controller/param-map.test.ts +237 -0
  156. package/tests/microservice/config-center.test.ts +77 -0
  157. package/tests/microservice/governance.test.ts +157 -0
  158. package/tests/microservice/monitoring.test.ts +75 -0
  159. package/tests/microservice/service-client.test.ts +136 -0
  160. package/tests/microservice/service-registry.test.ts +80 -0
  161. package/tests/microservice/tracing.test.ts +143 -0
  162. package/tests/utils/test-port.ts +29 -19
@@ -0,0 +1,118 @@
1
+ /**
2
+ * 服务调用指标
3
+ */
4
+ export interface ServiceCallMetrics {
5
+ /**
6
+ * 服务名
7
+ */
8
+ serviceName: string;
9
+
10
+ /**
11
+ * 实例标识(IP:Port)
12
+ */
13
+ instance: string;
14
+
15
+ /**
16
+ * 总请求数
17
+ */
18
+ totalRequests: number;
19
+
20
+ /**
21
+ * 成功请求数
22
+ */
23
+ successRequests: number;
24
+
25
+ /**
26
+ * 失败请求数
27
+ */
28
+ failureRequests: number;
29
+
30
+ /**
31
+ * 平均延迟(毫秒)
32
+ */
33
+ averageLatency: number;
34
+
35
+ /**
36
+ * 最小延迟(毫秒)
37
+ */
38
+ minLatency: number;
39
+
40
+ /**
41
+ * 最大延迟(毫秒)
42
+ */
43
+ maxLatency: number;
44
+
45
+ /**
46
+ * 错误率(0-1)
47
+ */
48
+ errorRate: number;
49
+
50
+ /**
51
+ * 最后更新时间(时间戳)
52
+ */
53
+ lastUpdateTime: number;
54
+ }
55
+
56
+ /**
57
+ * 服务实例健康状态
58
+ */
59
+ export interface ServiceInstanceHealth {
60
+ /**
61
+ * 服务名
62
+ */
63
+ serviceName: string;
64
+
65
+ /**
66
+ * 实例标识(IP:Port)
67
+ */
68
+ instance: string;
69
+
70
+ /**
71
+ * 是否健康
72
+ */
73
+ healthy: boolean;
74
+
75
+ /**
76
+ * 健康检查时间(时间戳)
77
+ */
78
+ checkTime: number;
79
+
80
+ /**
81
+ * 连续失败次数
82
+ */
83
+ consecutiveFailures: number;
84
+
85
+ /**
86
+ * 最后成功时间(时间戳)
87
+ */
88
+ lastSuccessTime?: number;
89
+
90
+ /**
91
+ * 最后失败时间(时间戳)
92
+ */
93
+ lastFailureTime?: number;
94
+ }
95
+
96
+ /**
97
+ * 监控配置选项
98
+ */
99
+ export interface MonitoringOptions {
100
+ /**
101
+ * 是否启用监控
102
+ * @default true
103
+ */
104
+ enabled?: boolean;
105
+
106
+ /**
107
+ * 指标收集间隔(毫秒)
108
+ * @default 60000
109
+ */
110
+ collectionInterval?: number;
111
+
112
+ /**
113
+ * 是否自动上报到 MetricsModule
114
+ * @default true
115
+ */
116
+ autoReportToMetrics?: boolean;
117
+ }
118
+
@@ -0,0 +1,107 @@
1
+ import 'reflect-metadata';
2
+ import type { ServiceCallOptions, ServiceCallResponse } from './types';
3
+ import type { Constructor } from '../../core/types';
4
+
5
+ /**
6
+ * 服务调用装饰器元数据键
7
+ */
8
+ const SERVICE_CALL_METADATA_KEY = Symbol('service-call:metadata');
9
+
10
+ /**
11
+ * 服务调用元数据
12
+ */
13
+ export interface ServiceCallMetadata {
14
+ /**
15
+ * 服务名
16
+ */
17
+ serviceName: string;
18
+
19
+ /**
20
+ * HTTP 方法
21
+ */
22
+ method: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';
23
+
24
+ /**
25
+ * 请求路径
26
+ */
27
+ path: string;
28
+
29
+ /**
30
+ * 服务调用选项
31
+ */
32
+ options?: Partial<ServiceCallOptions>;
33
+ }
34
+
35
+ /**
36
+ * ServiceCall 装饰器
37
+ * 用于标记服务调用方法,自动注入 ServiceClient 调用逻辑
38
+ *
39
+ * @example
40
+ * ```typescript
41
+ * @Injectable()
42
+ * class MyService {
43
+ * public constructor(
44
+ * @ServiceClient() private readonly serviceClient: ServiceClient,
45
+ * ) {}
46
+ *
47
+ * @ServiceCall('user-service', 'GET', '/api/users/:id')
48
+ * public async getUser(id: string): Promise<User> {
49
+ * // 自动调用 user-service 的 /api/users/:id 接口
50
+ * // 需要手动调用 serviceClient.call(),装饰器只提供元数据
51
+ * }
52
+ * }
53
+ * ```
54
+ *
55
+ * 注意:此装饰器主要用于标记和提供元数据,实际调用仍需要通过 ServiceClient
56
+ */
57
+ export function ServiceCall(
58
+ serviceName: string,
59
+ method: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH',
60
+ path: string,
61
+ options?: Partial<ServiceCallOptions>,
62
+ ): MethodDecorator {
63
+ return function (
64
+ target: object,
65
+ propertyKey: string | symbol,
66
+ descriptor: PropertyDescriptor,
67
+ ) {
68
+ const metadata: ServiceCallMetadata = {
69
+ serviceName,
70
+ method,
71
+ path,
72
+ options,
73
+ };
74
+
75
+ // 保存元数据
76
+ const existingMetadata: Map<string | symbol, ServiceCallMetadata> =
77
+ Reflect.getMetadata(SERVICE_CALL_METADATA_KEY, target.constructor) ||
78
+ new Map();
79
+ existingMetadata.set(propertyKey, metadata);
80
+ Reflect.defineMetadata(
81
+ SERVICE_CALL_METADATA_KEY,
82
+ existingMetadata,
83
+ target.constructor,
84
+ );
85
+
86
+ // 保存原始方法
87
+ const originalMethod = descriptor.value;
88
+
89
+ // 包装方法,添加服务调用元数据
90
+ descriptor.value = async function (...args: any[]) {
91
+ // 元数据可以通过 Reflect.getMetadata 获取
92
+ // 实际调用逻辑需要结合 ServiceClient 实现
93
+ // 这里只提供元数据标记,不自动执行调用
94
+ return originalMethod.apply(this, args);
95
+ };
96
+ };
97
+ }
98
+
99
+ /**
100
+ * 获取方法的服务调用元数据
101
+ */
102
+ export function getServiceCallMetadata(
103
+ target: Constructor<unknown>,
104
+ ): Map<string | symbol, ServiceCallMetadata> {
105
+ return Reflect.getMetadata(SERVICE_CALL_METADATA_KEY, target) || new Map();
106
+ }
107
+
@@ -0,0 +1,87 @@
1
+ import 'reflect-metadata';
2
+ import { ServiceClient as ServiceClientImpl } from './service-client';
3
+ import type { ServiceRegistry } from '../service-registry/types';
4
+ import { SERVICE_REGISTRY_TOKEN } from '../service-registry/types';
5
+ import { ControllerRegistry } from '../../controller/controller';
6
+ import type { Constructor } from '../../core/types';
7
+
8
+ /**
9
+ * ServiceClient 注入装饰器元数据键
10
+ */
11
+ const SERVICE_CLIENT_METADATA_KEY = Symbol('service-client:inject');
12
+
13
+ /**
14
+ * ServiceClient 装饰器
15
+ * 用于在类中注入 ServiceClient 实例
16
+ *
17
+ * @example
18
+ * ```typescript
19
+ * @Injectable()
20
+ * class MyService {
21
+ * public constructor(
22
+ * @ServiceClient() private readonly serviceClient: ServiceClient,
23
+ * ) {}
24
+ *
25
+ * public async callOtherService() {
26
+ * return await this.serviceClient.call({
27
+ * serviceName: 'other-service',
28
+ * path: '/api/data',
29
+ * method: 'GET',
30
+ * });
31
+ * }
32
+ * }
33
+ * ```
34
+ */
35
+ export function ServiceClient(): ParameterDecorator {
36
+ return function (
37
+ target: unknown,
38
+ _propertyKey: string | symbol | undefined,
39
+ parameterIndex: number,
40
+ ) {
41
+ const constructor = typeof target === 'function'
42
+ ? (target as Constructor<unknown>)
43
+ : (target as any)?.constructor;
44
+
45
+ if (!constructor) {
46
+ return;
47
+ }
48
+
49
+ // 保存元数据,标记该参数需要注入 ServiceClient
50
+ const existingMetadata: number[] =
51
+ Reflect.getMetadata(SERVICE_CLIENT_METADATA_KEY, constructor) || [];
52
+ existingMetadata.push(parameterIndex);
53
+ Reflect.defineMetadata(
54
+ SERVICE_CLIENT_METADATA_KEY,
55
+ existingMetadata,
56
+ constructor,
57
+ );
58
+ };
59
+ }
60
+
61
+ /**
62
+ * 创建 ServiceClient 实例
63
+ */
64
+ export function createServiceClient(): ServiceClientImpl {
65
+ const container = ControllerRegistry.getInstance().getContainer();
66
+ const serviceRegistry = container.resolve<ServiceRegistry>(
67
+ SERVICE_REGISTRY_TOKEN,
68
+ );
69
+
70
+ if (!serviceRegistry) {
71
+ throw new Error(
72
+ 'ServiceRegistry not found. Please register ServiceRegistryModule first.',
73
+ );
74
+ }
75
+
76
+ return new ServiceClientImpl(serviceRegistry);
77
+ }
78
+
79
+ /**
80
+ * 获取需要注入 ServiceClient 的参数索引列表
81
+ */
82
+ export function getServiceClientParameterIndices(
83
+ target: Constructor<unknown>,
84
+ ): number[] {
85
+ return Reflect.getMetadata(SERVICE_CLIENT_METADATA_KEY, target) || [];
86
+ }
87
+
@@ -0,0 +1,37 @@
1
+ export { ServiceClient } from './service-client';
2
+ export {
3
+ LoadBalancerFactory,
4
+ RandomLoadBalancer,
5
+ RoundRobinLoadBalancer,
6
+ WeightedRoundRobinLoadBalancer,
7
+ ConsistentHashLoadBalancer,
8
+ LeastActiveLoadBalancer,
9
+ } from './load-balancer';
10
+ export {
11
+ TraceIdRequestInterceptor,
12
+ UserInfoRequestInterceptor,
13
+ RequestLogInterceptor,
14
+ ResponseLogInterceptor,
15
+ ResponseTransformInterceptor,
16
+ ErrorHandlerInterceptor,
17
+ } from './interceptors';
18
+ export {
19
+ ServiceClient as ServiceClientDecorator,
20
+ createServiceClient,
21
+ getServiceClientParameterIndices,
22
+ } from './decorators';
23
+ export {
24
+ ServiceCall,
25
+ getServiceCallMetadata,
26
+ type ServiceCallMetadata,
27
+ } from './call-decorators';
28
+ export type {
29
+ LoadBalanceStrategy,
30
+ LoadBalancer,
31
+ ServiceCallOptions,
32
+ ServiceCallResponse,
33
+ ServiceRequestInterceptor,
34
+ ServiceResponseInterceptor,
35
+ ServiceCallError,
36
+ } from './types';
37
+
@@ -0,0 +1,182 @@
1
+ import type {
2
+ ServiceCallOptions,
3
+ ServiceCallResponse,
4
+ ServiceRequestInterceptor,
5
+ ServiceResponseInterceptor,
6
+ } from './types';
7
+
8
+ /**
9
+ * 追踪 ID 请求拦截器
10
+ * 自动在请求头中添加追踪 ID
11
+ */
12
+ export class TraceIdRequestInterceptor implements ServiceRequestInterceptor {
13
+ private readonly headerName: string;
14
+ private readonly traceIdGenerator: () => string;
15
+
16
+ public constructor(options?: {
17
+ /**
18
+ * 追踪 ID 请求头名称
19
+ * @default 'X-Trace-Id'
20
+ */
21
+ headerName?: string;
22
+
23
+ /**
24
+ * 追踪 ID 生成器
25
+ * @default 生成 UUID v4
26
+ */
27
+ traceIdGenerator?: () => string;
28
+ }) {
29
+ this.headerName = options?.headerName ?? 'X-Trace-Id';
30
+ this.traceIdGenerator = options?.traceIdGenerator ?? this.generateTraceId;
31
+ }
32
+
33
+ public intercept(options: ServiceCallOptions): ServiceCallOptions {
34
+ const traceId = this.traceIdGenerator();
35
+ return {
36
+ ...options,
37
+ headers: {
38
+ ...options.headers,
39
+ [this.headerName]: traceId,
40
+ },
41
+ };
42
+ }
43
+
44
+ /**
45
+ * 生成追踪 ID(UUID v4 简化版)
46
+ */
47
+ private generateTraceId(): string {
48
+ return `${Date.now()}-${Math.random().toString(36).substring(2, 15)}`;
49
+ }
50
+ }
51
+
52
+ /**
53
+ * 用户信息请求拦截器
54
+ * 自动在请求头中添加用户信息
55
+ */
56
+ export class UserInfoRequestInterceptor implements ServiceRequestInterceptor {
57
+ private readonly headerName: string;
58
+ private readonly userInfoProvider: () => string | undefined;
59
+
60
+ public constructor(options: {
61
+ /**
62
+ * 用户信息请求头名称
63
+ * @default 'X-User-Info'
64
+ */
65
+ headerName?: string;
66
+
67
+ /**
68
+ * 用户信息提供者
69
+ */
70
+ userInfoProvider: () => string | undefined;
71
+ }) {
72
+ this.headerName = options.headerName ?? 'X-User-Info';
73
+ this.userInfoProvider = options.userInfoProvider;
74
+ }
75
+
76
+ public intercept(options: ServiceCallOptions): ServiceCallOptions {
77
+ const userInfo = this.userInfoProvider();
78
+ if (!userInfo) {
79
+ return options;
80
+ }
81
+
82
+ return {
83
+ ...options,
84
+ headers: {
85
+ ...options.headers,
86
+ [this.headerName]: userInfo,
87
+ },
88
+ };
89
+ }
90
+ }
91
+
92
+ /**
93
+ * 请求日志拦截器
94
+ * 记录请求日志
95
+ */
96
+ export class RequestLogInterceptor implements ServiceRequestInterceptor {
97
+ private readonly logger?: (message: string) => void;
98
+
99
+ public constructor(options?: {
100
+ /**
101
+ * 日志记录器
102
+ */
103
+ logger?: (message: string) => void;
104
+ }) {
105
+ this.logger = options?.logger ?? console.log;
106
+ }
107
+
108
+ public intercept(options: ServiceCallOptions): ServiceCallOptions {
109
+ if (this.logger) {
110
+ this.logger(
111
+ `[ServiceClient] Request: ${options.method} ${options.serviceName}${options.path}`,
112
+ );
113
+ }
114
+ return options;
115
+ }
116
+ }
117
+
118
+ /**
119
+ * 响应日志拦截器
120
+ * 记录响应日志
121
+ */
122
+ export class ResponseLogInterceptor implements ServiceResponseInterceptor {
123
+ private readonly logger?: (message: string) => void;
124
+
125
+ public constructor(options?: {
126
+ /**
127
+ * 日志记录器
128
+ */
129
+ logger?: (message: string) => void;
130
+ }) {
131
+ this.logger = options?.logger ?? console.log;
132
+ }
133
+
134
+ public intercept<T>(response: ServiceCallResponse<T>): ServiceCallResponse<T> {
135
+ if (this.logger) {
136
+ this.logger(
137
+ `[ServiceClient] Response: ${response.status} from ${response.instance.ip}:${response.instance.port}`,
138
+ );
139
+ }
140
+ return response;
141
+ }
142
+ }
143
+
144
+ /**
145
+ * 响应数据转换拦截器
146
+ * 转换响应数据格式
147
+ *
148
+ * 注意:这个拦截器会改变响应数据的类型,因此需要类型断言
149
+ */
150
+ export class ResponseTransformInterceptor<TInput = unknown, TOutput = unknown> {
151
+ private readonly transformer: (data: TInput) => TOutput;
152
+
153
+ public constructor(transformer: (data: TInput) => TOutput) {
154
+ this.transformer = transformer;
155
+ }
156
+
157
+ /**
158
+ * 拦截响应并转换数据
159
+ */
160
+ public intercept<T>(response: ServiceCallResponse<T>): ServiceCallResponse<TOutput> {
161
+ return {
162
+ ...response,
163
+ data: this.transformer(response.data as unknown as TInput),
164
+ } as ServiceCallResponse<TOutput>;
165
+ }
166
+ }
167
+
168
+ /**
169
+ * 错误处理拦截器
170
+ * 统一处理错误响应
171
+ */
172
+ export class ErrorHandlerInterceptor implements ServiceResponseInterceptor {
173
+ public intercept<T>(response: ServiceCallResponse<T>): ServiceCallResponse<T> {
174
+ // 如果状态码表示错误,可以在这里进行统一处理
175
+ // 例如:记录错误日志、转换错误格式等
176
+ if (response.status >= 400) {
177
+ // 可以在这里添加错误处理逻辑
178
+ }
179
+ return response;
180
+ }
181
+ }
182
+