@be-link/ecommerce-trade-service-node-sdk 0.1.58 → 0.1.59

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/enums.d.ts CHANGED
@@ -229,6 +229,23 @@ export declare namespace ENUM {
229
229
  /** 商家手动退款 */
230
230
  MERCHANT_MANUAL = "MERCHANT_MANUAL"
231
231
  }
232
+ /**
233
+ * 直播状态
234
+ * - 1:直播中。
235
+ * - 2:预告。
236
+ * - 3:回放。
237
+ * - 4:结束。
238
+ */
239
+ enum LiveRoomStatus {
240
+ /** 直播中 */
241
+ LIVE = "1",
242
+ /** 预告 */
243
+ PREVIEW = "2",
244
+ /** 回放 */
245
+ PLAYBACK = "3",
246
+ /** 结束 */
247
+ ENDED = "4"
248
+ }
232
249
  }
233
250
  /** RabbitMQ 交换机路由枚举 */
234
251
  export declare namespace EXCHANGE_ENUM {
package/enums.js CHANGED
@@ -260,6 +260,24 @@ var ENUM;
260
260
  /** 商家手动退款 */
261
261
  ReverseRefundHandlerEnum["MERCHANT_MANUAL"] = "MERCHANT_MANUAL";
262
262
  })(ReverseRefundHandlerEnum = ENUM.ReverseRefundHandlerEnum || (ENUM.ReverseRefundHandlerEnum = {}));
263
+ /**
264
+ * 直播状态
265
+ * - 1:直播中。
266
+ * - 2:预告。
267
+ * - 3:回放。
268
+ * - 4:结束。
269
+ */
270
+ let LiveRoomStatus;
271
+ (function (LiveRoomStatus) {
272
+ /** 直播中 */
273
+ LiveRoomStatus["LIVE"] = "1";
274
+ /** 预告 */
275
+ LiveRoomStatus["PREVIEW"] = "2";
276
+ /** 回放 */
277
+ LiveRoomStatus["PLAYBACK"] = "3";
278
+ /** 结束 */
279
+ LiveRoomStatus["ENDED"] = "4";
280
+ })(LiveRoomStatus = ENUM.LiveRoomStatus || (ENUM.LiveRoomStatus = {}));
263
281
  })(ENUM || (exports.ENUM = ENUM = {}));
264
282
  /** RabbitMQ 交换机路由枚举 */
265
283
  var EXCHANGE_ENUM;
@@ -84,6 +84,8 @@ export declare namespace PosCoreService {
84
84
  skuId: string;
85
85
  /** 直播间ID */
86
86
  liveRoomId?: string;
87
+ /** 直播间状态 */
88
+ liveRoomStatus?: ENUM.LiveRoomStatus;
87
89
  /** 订单来源类型k */
88
90
  source: ENUM.OrderSource;
89
91
  /** 订单来源平台类型 */
@@ -312,6 +312,9 @@ export declare namespace PosOrderQueryService {
312
312
  };
313
313
  user: {
314
314
  userId: string;
315
+ unionId: string;
316
+ /** 用户昵称 */
317
+ nickname?: string;
315
318
  memberLevel?: string;
316
319
  receiverName: string;
317
320
  receiverPhone: string;
@@ -326,6 +329,9 @@ export declare namespace PosOrderQueryService {
326
329
  };
327
330
  userDetail: {
328
331
  userId: string;
332
+ unionId: string;
333
+ /** 用户昵称 */
334
+ nickname?: string;
329
335
  memberLevel?: string;
330
336
  receiverName: string;
331
337
  receiverPhone: string;
@@ -6,16 +6,35 @@ export declare namespace RosOrderQueryService {
6
6
  interface IOrderList {
7
7
  /** 查询条件 */
8
8
  conditions?: {
9
- createdAt: string;
10
- operateTime: string;
11
- orderTime: string;
12
- status: ENUM.ReverseOrderStatus;
13
- arrivalStatusList: ENUM.ReverseArrivalStatus[];
14
- wayList: ENUM.ReverseRefundWay[];
15
- typeList: ENUM.ReverseRefundType[];
16
- userIds: string[];
17
- orderIds: string[];
18
- storeIds: string[];
9
+ /** 下单时间范围 */
10
+ createdAt?: {
11
+ start?: number;
12
+ end?: number;
13
+ };
14
+ /** 退款操作时间范围 */
15
+ operateTime?: {
16
+ start?: number;
17
+ end?: number;
18
+ };
19
+ /** 退款申请时间范围 */
20
+ orderTime?: {
21
+ start?: number;
22
+ end?: number;
23
+ };
24
+ /** 退款订单状态列表 */
25
+ statusList?: ENUM.ReverseOrderStatus[];
26
+ /** 退款到账状态列表 */
27
+ arrivalStatusList?: ENUM.ReverseArrivalStatus[];
28
+ /** 退款方式列表 */
29
+ wayList?: ENUM.ReverseRefundWay[];
30
+ /** 退款类型列表 */
31
+ typeList?: ENUM.ReverseRefundType[];
32
+ /** 用户ID列表 */
33
+ userIds?: string[];
34
+ /** 正向订单ID列表 */
35
+ orderIds?: string[];
36
+ /** 门店ID列表 */
37
+ storeIds?: string[];
19
38
  };
20
39
  /** 分页 */
21
40
  pagination: {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@be-link/ecommerce-trade-service-node-sdk",
3
- "version": "0.1.58",
3
+ "version": "0.1.59",
4
4
  "description": "EcommerceTradeService Node.js SDK",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
package/types.d.ts CHANGED
@@ -154,6 +154,7 @@ export interface ITradeReverseOrder {
154
154
  isFullRefund: number;
155
155
  createdAt: number;
156
156
  updatedAt: number;
157
+ orderItemIds: string[];
157
158
  }
158
159
  /** 资源扩展信息类型 */
159
160
  export interface IBizExtraInfo {
package/utils/http.d.ts CHANGED
@@ -9,27 +9,3 @@ declare module '@fastify/request-context' {
9
9
  }
10
10
  }
11
11
  export declare function callApi<T extends (...args: any[]) => Promise<any>>(url: string, request?: Parameters<T>[0]): Promise<Awaited<ReturnType<T>>>;
12
- export declare function getConnectionStats(): {
13
- activeRequests: number;
14
- totalRequests: number;
15
- peakActiveRequests: number;
16
- httpSockets: {
17
- total: number;
18
- hosts: number;
19
- details: NodeJS.ReadOnlyDict<import("net").Socket[]>;
20
- };
21
- httpsSockets: {
22
- total: number;
23
- hosts: number;
24
- details: NodeJS.ReadOnlyDict<import("net").Socket[]>;
25
- };
26
- config: {
27
- maxSockets: number;
28
- maxTotalSockets: number;
29
- requestTimeout: number;
30
- note: string;
31
- };
32
- };
33
- export declare function resetPeakStats(): void;
34
- export declare function startMonitoring(interval?: number): void;
35
- export declare function stopMonitoring(): void;
package/utils/http.js CHANGED
@@ -1,120 +1,68 @@
1
1
  "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
2
35
  var __importDefault = (this && this.__importDefault) || function (mod) {
3
36
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
37
  };
5
38
  Object.defineProperty(exports, "__esModule", { value: true });
6
39
  exports.callApi = callApi;
7
- exports.getConnectionStats = getConnectionStats;
8
- exports.resetPeakStats = resetPeakStats;
9
- exports.startMonitoring = startMonitoring;
10
- exports.stopMonitoring = stopMonitoring;
11
40
  const axios_1 = __importDefault(require("axios"));
12
41
  const uuid_1 = require("uuid");
13
42
  const axios_retry_1 = __importDefault(require("axios-retry"));
14
43
  const request_context_1 = require("@fastify/request-context");
15
- const http_1 = __importDefault(require("http"));
16
- const https_1 = __importDefault(require("https"));
17
44
  const safe_stable_stringify_1 = __importDefault(require("safe-stable-stringify"));
18
- // 针对高并发优化配置 - 支持2000并发
19
- const HTTP_CONFIG = {
20
- maxSockets: 2000, // 每个主机的最大socket连接数(支持2000并发)
21
- maxFreeSockets: 1000, // 空闲socket保留数(50%复用率,提高连接复用效率)
22
- maxTotalSockets: 3000, // 所有主机总socket数(单后端场景优化)
23
- keepAliveMsecs: 30000, // 保持连接30秒(平衡资源占用和连接复用)
24
- timeout: 3000, // socket超时3秒(高并发场景快速失败)
25
- requestTimeout: 30000, // 请求超时3秒(快速释放资源,避免慢请求占用连接)
26
- retryBaseDelay: 100, // 基础重试延迟100ms(给服务恢复时间)
27
- logThreshold: 1000, // 日志采样率(每1000个请求采样1次,降低日志开销)
28
- monitorInterval: 5000, // 监控日志间隔(毫秒)
29
- };
30
- // 配置 HTTP/HTTPS Agent 以支持高并发连接池和 keepAlive
31
- const httpAgent = new http_1.default.Agent({
32
- keepAlive: true,
33
- keepAliveMsecs: HTTP_CONFIG.keepAliveMsecs,
34
- maxSockets: HTTP_CONFIG.maxSockets,
35
- maxFreeSockets: HTTP_CONFIG.maxFreeSockets,
36
- maxTotalSockets: HTTP_CONFIG.maxTotalSockets,
37
- timeout: HTTP_CONFIG.timeout,
38
- scheduling: 'fifo', // 先进先出调度
39
- });
40
- const httpsAgent = new https_1.default.Agent({
41
- keepAlive: true,
42
- keepAliveMsecs: HTTP_CONFIG.keepAliveMsecs,
43
- maxSockets: HTTP_CONFIG.maxSockets,
44
- maxFreeSockets: HTTP_CONFIG.maxFreeSockets,
45
- maxTotalSockets: HTTP_CONFIG.maxTotalSockets,
46
- timeout: HTTP_CONFIG.timeout,
47
- scheduling: 'fifo',
48
- });
49
- // 配置 axios 默认使用这些 agent
50
- axios_1.default.defaults.httpAgent = httpAgent;
51
- axios_1.default.defaults.httpsAgent = httpsAgent;
52
- axios_1.default.defaults.timeout = HTTP_CONFIG.requestTimeout;
53
- axios_1.default.defaults.maxRedirects = 3; // 限制重定向次数
54
- axios_1.default.defaults.maxContentLength = 50 * 1024 * 1024; // 50MB 最大响应大小
55
- // 高并发场景下的智能重试配置
56
45
  (0, axios_retry_1.default)(axios_1.default, {
46
+ retries: 1,
57
47
  retryCondition(error) {
58
- // 重试临时错误和特定的网络错误
59
- const status = error.response?.status;
60
- const isNetworkError = error.code === 'ECONNRESET' || error.code === 'ETIMEDOUT';
61
- const isServerError = status === 502 || status === 503 || status === 504;
62
- const isRateLimited = status === 429;
63
- return isNetworkError || isServerError || isRateLimited;
48
+ return error.response?.status === 502;
64
49
  },
65
- retryDelay: (retryCount, error) => {
66
- // 指数退避 + 抖动
67
- const status = error.response?.status;
68
- // 如果是限流错误,延迟更长
69
- if (status === 429) {
70
- const retryAfter = error.response?.headers['retry-after'];
71
- if (retryAfter) {
72
- return parseInt(retryAfter) * 1000;
73
- }
74
- return 1000 + Math.random() * 1000; // 1-2秒
75
- }
76
- // 指数退避:100ms, 200ms, 400ms...
77
- const exponentialDelay = HTTP_CONFIG.retryBaseDelay * Math.pow(2, retryCount - 1);
78
- const jitter = Math.random() * 50; // 0-50ms 抖动
79
- return Math.min(exponentialDelay + jitter, 2000); // 最多延迟2秒
50
+ retryDelay: (retryCount) => {
51
+ console.info(`retryCount: ${retryCount}, retryDelay: ${retryCount * 500}`);
52
+ return retryCount * 500;
53
+ },
54
+ onRetry(retryCount, error, requestConfig) {
55
+ console.info(`retryCount: ${retryCount}, onRetry: ${error.message}, requestHeader: ${(0, safe_stable_stringify_1.default)(requestConfig.headers)}`);
80
56
  },
81
- shouldResetTimeout: true, // 重试时重置超时
82
57
  });
83
- // 连接池状态监控
84
- let requestCount = 0;
85
- let activeRequests = 0;
86
- let peakActiveRequests = 0; // 峰值并发
87
- // 注意:已移除应用层并发队列限制,完全依赖底层socket连接池控制
88
- // 这样可以避免应用层排队等待,充分利用socket连接池的并发能力
89
58
  async function callApi(url, request) {
90
- // 不再等待应用层队列,直接发起请求,由底层socket连接池控制并发
91
- const currentRequestId = ++requestCount;
92
- activeRequests++;
93
- // 记录峰值并发
94
- if (activeRequests > peakActiveRequests) {
95
- peakActiveRequests = activeRequests;
96
- }
97
- // 批量获取请求上下文,减少函数调用开销
98
- const ctx = request_context_1.requestContext.get('requestId') ? request_context_1.requestContext : null;
99
- const requestId = ctx?.get('requestId') || ctx?.get('traceMessageId') || (0, uuid_1.v4)();
100
- const pandoraUserId = ctx?.get('pandoraUserId') || '';
101
- const beLinkUserId = ctx?.get('beLinkUserId') || '';
102
- const pandoraRoleId = ctx?.get('pandoraRoleId') || '';
103
- const realIp = ctx?.get('realIp') || '';
104
- // 采样日志决策(提前计算,避免重复判断)
105
- const shouldLog = currentRequestId % HTTP_CONFIG.logThreshold === 0;
106
- const startTime = shouldLog ? Date.now() : 0;
59
+ const requestId = request_context_1.requestContext.get('requestId') || request_context_1.requestContext.get('traceMessageId') || (0, uuid_1.v4)();
60
+ const pandoraUserId = request_context_1.requestContext.get('pandoraUserId') || '';
61
+ const beLinkUserId = request_context_1.requestContext.get('beLinkUserId') || '';
62
+ const pandoraRoleId = request_context_1.requestContext.get('pandoraRoleId') || '';
63
+ const realIp = request_context_1.requestContext.get('realIp') || '';
107
64
  try {
108
- if (shouldLog) {
109
- console.log((0, safe_stable_stringify_1.default)({
110
- message: '发起HTTP请求',
111
- currentRequestId,
112
- activeRequests,
113
- requestId,
114
- url,
115
- type: 'http_request_start',
116
- }));
117
- }
65
+ console.info(`准备发起ecommerce-trade-service请求[${requestId}]: ${url}, 参数: ${(0, safe_stable_stringify_1.default)(request)}`);
118
66
  const response = await axios_1.default.post(url, request, {
119
67
  headers: {
120
68
  'x-request-id': requestId,
@@ -122,160 +70,42 @@ async function callApi(url, request) {
122
70
  'x-belink-userid': beLinkUserId,
123
71
  'x-belink-pandora-roleid': pandoraRoleId,
124
72
  'x-real-ip': realIp,
125
- Connection: 'keep-alive',
126
73
  },
127
- timeout: HTTP_CONFIG.requestTimeout,
128
- httpAgent,
129
- httpsAgent,
130
74
  });
131
- if (shouldLog) {
132
- const duration = Date.now() - startTime;
133
- if (duration > 3000) {
134
- console.log((0, safe_stable_stringify_1.default)({
135
- message: '请求完成',
136
- currentRequestId,
137
- duration: `${duration}ms`,
138
- activeRequests,
139
- type: 'http_request_complete',
140
- }));
141
- }
142
- }
143
75
  const responseData = response.data;
144
76
  return responseData.data;
145
77
  }
146
78
  catch (error) {
147
79
  const axiosError = error;
148
- const duration = startTime ? Date.now() - startTime : 0;
149
- // 错误始终记录(但简化输出)
150
- console.error((0, safe_stable_stringify_1.default)({
151
- message: '请求失败',
152
- currentRequestId,
153
- url,
154
- duration: `${duration}ms`,
155
- activeRequests,
156
- errorMessage: axiosError.message,
157
- type: 'http_request_failed',
158
- }));
159
80
  if (axiosError.response) {
160
81
  const response = axiosError.response;
161
82
  const data = response.data;
162
- console.error((0, safe_stable_stringify_1.default)({
163
- message: '响应异常',
164
- status: response.status,
165
- errorMessage: data?.message || axiosError.message,
166
- type: 'http_response_error',
167
- }));
83
+ console.error(`ecommerce-trade-service 异常: ${axiosError.message},requestId: ${requestId}`);
84
+ console.info('响应信息', data.message);
85
+ console.error('异常堆栈', (0, safe_stable_stringify_1.default)(error.stack));
86
+ // throw new Error(data.errorType + ' - ' + data.message)
87
+ throw error;
168
88
  }
169
- throw error;
170
- }
171
- finally {
172
- // 记录请求完成,减少活跃计数
173
- activeRequests--;
174
- }
175
- }
176
- // 导出监控函数
177
- function getConnectionStats() {
178
- const stats = {
179
- // 当前状态
180
- activeRequests,
181
- totalRequests: requestCount,
182
- // 峰值指标
183
- peakActiveRequests,
184
- // Socket连接池状态(这是真正的并发控制点)
185
- httpSockets: {
186
- total: Object.keys(httpAgent.sockets).reduce((sum, host) => sum + (httpAgent.sockets[host]?.length || 0), 0),
187
- hosts: Object.keys(httpAgent.sockets).length,
188
- details: httpAgent.sockets,
189
- },
190
- httpsSockets: {
191
- total: Object.keys(httpsAgent.sockets).reduce((sum, host) => sum + (httpsAgent.sockets[host]?.length || 0), 0),
192
- hosts: Object.keys(httpsAgent.sockets).length,
193
- details: httpsAgent.sockets,
194
- },
195
- // 配置信息
196
- config: {
197
- maxSockets: HTTP_CONFIG.maxSockets,
198
- maxTotalSockets: HTTP_CONFIG.maxTotalSockets,
199
- requestTimeout: HTTP_CONFIG.requestTimeout,
200
- note: '已移除应用层并发队列限制,完全依赖socket连接池',
201
- },
202
- };
203
- return stats;
204
- }
205
- // 重置峰值统计(可用于定期重置)
206
- function resetPeakStats() {
207
- peakActiveRequests = activeRequests;
208
- console.log((0, safe_stable_stringify_1.default)({
209
- message: '峰值统计已重置',
210
- type: 'stats_reset',
211
- }));
212
- }
213
- // 定期监控日志
214
- let monitorTimer = null;
215
- function startMonitoring(interval = HTTP_CONFIG.monitorInterval) {
216
- if (monitorTimer) {
217
- console.log((0, safe_stable_stringify_1.default)({
218
- message: '监控已在运行中',
219
- type: 'monitor_already_running',
220
- }));
221
- return;
222
- }
223
- console.log((0, safe_stable_stringify_1.default)({
224
- message: '启动并发监控',
225
- interval: `${interval}ms`,
226
- type: 'monitor_start',
227
- }));
228
- monitorTimer = setInterval(() => {
229
- const stats = getConnectionStats();
230
- // 只在有活动时打印
231
- if (stats.totalRequests === 0) {
232
- return;
233
- }
234
- // 检测异常情况(基于socket连接池使用率)
235
- const httpSocketsUsage = stats.httpSockets.total / HTTP_CONFIG.maxSockets;
236
- const httpsSocketsUsage = stats.httpsSockets.total / HTTP_CONFIG.maxSockets;
237
- const maxSocketUsage = Math.max(httpSocketsUsage, httpsSocketsUsage);
238
- // Socket连接池使用率超过80%视为瓶颈
239
- const hasIssue = maxSocketUsage > 0.8;
240
- if (hasIssue) {
241
- console.warn((0, safe_stable_stringify_1.default)({
242
- message: '并发监控检测到瓶颈',
243
- 当前并发: stats.activeRequests,
244
- 峰值并发: stats.peakActiveRequests,
245
- 总请求数: stats.totalRequests,
246
- HTTP_Sockets: `${stats.httpSockets.total}/${HTTP_CONFIG.maxSockets} (${Math.round(httpSocketsUsage * 100)}%)`,
247
- HTTPS_Sockets: `${stats.httpsSockets.total}/${HTTP_CONFIG.maxSockets} (${Math.round(httpsSocketsUsage * 100)}%)`,
248
- 建议: 'Socket连接池接近饱和,考虑提高maxSockets配置',
249
- type: 'monitor_bottleneck_detected',
250
- }));
89
+ // 调用dns模块解析url
90
+ const dns = await Promise.resolve().then(() => __importStar(require('dns')));
91
+ const dnsPromise = new Promise((resolve, reject) => {
92
+ const lookupRes = dns.lookup(url, (err, address) => {
93
+ if (err) {
94
+ console.error(err.message);
95
+ reject(err);
96
+ }
97
+ console.info(`lookup: ${(0, safe_stable_stringify_1.default)(lookupRes)}`);
98
+ resolve(address);
99
+ });
100
+ });
101
+ try {
102
+ const address = await dnsPromise;
103
+ console.info(`address: ${(0, safe_stable_stringify_1.default)(address)}`);
251
104
  }
252
- else if (stats.totalRequests % 10000 === 0) {
253
- // 每1万次请求打印一次正常状态
254
- console.log((0, safe_stable_stringify_1.default)({
255
- message: '并发监控运行正常',
256
- 总请求: stats.totalRequests,
257
- 当前并发: stats.activeRequests,
258
- 峰值并发: stats.peakActiveRequests,
259
- HTTP_Sockets使用率: `${Math.round(httpSocketsUsage * 100)}%`,
260
- HTTPS_Sockets使用率: `${Math.round(httpsSocketsUsage * 100)}%`,
261
- type: 'monitor_normal',
262
- }));
105
+ catch (error) {
106
+ console.info(`error: ${(0, safe_stable_stringify_1.default)(error)}`);
263
107
  }
264
- }, interval);
265
- }
266
- function stopMonitoring() {
267
- if (monitorTimer) {
268
- clearInterval(monitorTimer);
269
- monitorTimer = null;
270
- console.log((0, safe_stable_stringify_1.default)({
271
- message: '监控已停止',
272
- type: 'monitor_stop',
273
- }));
108
+ console.error(`ecommerce-trade-service 未知异常: ${axiosError.message}`, error.stack);
109
+ throw error;
274
110
  }
275
111
  }
276
- // 自动启动监控(可选,如果不想自动启动可以注释掉)
277
- if (process.env.NODE_ENV !== 'test') {
278
- setTimeout(() => {
279
- startMonitoring();
280
- }, 3000); // 延迟3秒启动,避免服务启动时的干扰
281
- }