@machinemetrics/mm-erp-sdk 0.1.9-beta.1 → 0.1.9-beta.2
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/README.md +5 -0
- package/dist/{config-CvA-mFWF.js → config-Bax6Ofp5.js} +2 -2
- package/dist/{config-CvA-mFWF.js.map → config-Bax6Ofp5.js.map} +1 -1
- package/dist/{connector-factory-BPm2GVVF.js → connector-factory-BaMIlES8.js} +2 -2
- package/dist/{connector-factory-BPm2GVVF.js.map → connector-factory-BaMIlES8.js.map} +1 -1
- package/dist/{hashed-cache-manager-B15NN8hK.js → hashed-cache-manager-C1u9jQgY.js} +4 -4
- package/dist/{hashed-cache-manager-B15NN8hK.js.map → hashed-cache-manager-C1u9jQgY.js.map} +1 -1
- package/dist/{index-D8qO1NyK.js → index-BkVlW0ZW.js} +2 -2
- package/dist/{index-D8qO1NyK.js.map → index-BkVlW0ZW.js.map} +1 -1
- package/dist/index.d.ts +1 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/{logger-BWw0_z9q.js → logger-DW5fyhVS.js} +114 -78
- package/dist/logger-DW5fyhVS.js.map +1 -0
- package/dist/mm-erp-sdk.js +7 -716
- package/dist/mm-erp-sdk.js.map +1 -1
- package/dist/services/data-sync-service/data-sync-service.d.ts.map +1 -1
- package/dist/services/data-sync-service/jobs/clean-up-expired-cache.js +4 -4
- package/dist/services/data-sync-service/jobs/from-erp.d.ts.map +1 -1
- package/dist/services/data-sync-service/jobs/from-erp.js +12 -5
- package/dist/services/data-sync-service/jobs/from-erp.js.map +1 -1
- package/dist/services/data-sync-service/jobs/retry-failed-labor-tickets.js +3 -3
- package/dist/services/data-sync-service/jobs/run-migrations.js +1 -1
- package/dist/services/data-sync-service/jobs/to-erp.d.ts.map +1 -1
- package/dist/services/data-sync-service/jobs/to-erp.js +4 -7
- package/dist/services/data-sync-service/jobs/to-erp.js.map +1 -1
- package/dist/services/mm-api-service/index.d.ts +0 -7
- package/dist/services/mm-api-service/index.d.ts.map +1 -1
- package/dist/services/mm-api-service/mm-api-service.d.ts +0 -6
- package/dist/services/mm-api-service/mm-api-service.d.ts.map +1 -1
- package/dist/services/reporting-service/logger.d.ts.map +1 -1
- package/dist/utils/index.d.ts +0 -5
- package/dist/utils/index.d.ts.map +1 -1
- package/package.json +2 -5
- package/src/index.ts +0 -3
- package/src/services/data-sync-service/data-sync-service.ts +0 -10
- package/src/services/data-sync-service/jobs/from-erp.ts +7 -2
- package/src/services/data-sync-service/jobs/to-erp.ts +1 -5
- package/src/services/mm-api-service/index.ts +0 -8
- package/src/services/mm-api-service/mm-api-service.ts +2 -19
- package/src/services/reporting-service/logger.ts +111 -81
- package/src/utils/index.ts +0 -6
- package/dist/logger-BWw0_z9q.js.map +0 -1
- package/dist/services/data-sync-service/nats-labor-ticket-listener.d.ts +0 -30
- package/dist/services/data-sync-service/nats-labor-ticket-listener.d.ts.map +0 -1
- package/dist/services/mm-api-service/company-info.d.ts +0 -13
- package/dist/services/mm-api-service/company-info.d.ts.map +0 -1
- package/dist/services/nats-service/nats-service.d.ts +0 -114
- package/dist/services/nats-service/nats-service.d.ts.map +0 -1
- package/dist/services/nats-service/test-nats-subscriber.d.ts +0 -6
- package/dist/services/nats-service/test-nats-subscriber.d.ts.map +0 -1
- package/dist/utils/error-formatter.d.ts +0 -19
- package/dist/utils/error-formatter.d.ts.map +0 -1
- package/src/services/data-sync-service/nats-labor-ticket-listener.ts +0 -341
- package/src/services/mm-api-service/company-info.ts +0 -87
- package/src/services/nats-service/nats-service.ts +0 -351
- package/src/services/nats-service/test-nats-subscriber.ts +0 -96
- package/src/utils/error-formatter.ts +0 -205
|
@@ -1,351 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* NATS Service - Central connection and subscription management
|
|
3
|
-
* Allows connectors to register handlers for different NATS subjects
|
|
4
|
-
*/
|
|
5
|
-
|
|
6
|
-
import { connect, NatsConnection, StringCodec, Subscription } from "nats";
|
|
7
|
-
import { logger } from "../reporting-service";
|
|
8
|
-
|
|
9
|
-
const sc = StringCodec();
|
|
10
|
-
|
|
11
|
-
export interface NatsMessageHandler {
|
|
12
|
-
/**
|
|
13
|
-
* Handler function for NATS messages
|
|
14
|
-
* - Return a value to reply (if msg has reply subject)
|
|
15
|
-
* - Return void/undefined for pub-sub (no reply)
|
|
16
|
-
*/
|
|
17
|
-
handle: (data: any, subject: string) => Promise<any | void>;
|
|
18
|
-
}
|
|
19
|
-
|
|
20
|
-
export interface NatsHandlerRegistration {
|
|
21
|
-
/**
|
|
22
|
-
* Subject pattern to subscribe to (supports wildcards: *, >)
|
|
23
|
-
* Examples:
|
|
24
|
-
* - "mm.14.epic01.labor-ticket.*" (single level wildcard)
|
|
25
|
-
* - "mm.14.epic01.erp.>" (multi-level wildcard)
|
|
26
|
-
*/
|
|
27
|
-
subject: string;
|
|
28
|
-
|
|
29
|
-
/**
|
|
30
|
-
* Handler for this subject
|
|
31
|
-
*/
|
|
32
|
-
handler: NatsMessageHandler;
|
|
33
|
-
|
|
34
|
-
/**
|
|
35
|
-
* Optional description for logging/debugging
|
|
36
|
-
*/
|
|
37
|
-
description?: string;
|
|
38
|
-
}
|
|
39
|
-
|
|
40
|
-
export interface NatsServiceConfig {
|
|
41
|
-
/**
|
|
42
|
-
* NATS server URLs
|
|
43
|
-
*/
|
|
44
|
-
servers: string | string[];
|
|
45
|
-
|
|
46
|
-
/**
|
|
47
|
-
* Connection name (for monitoring)
|
|
48
|
-
*/
|
|
49
|
-
name: string;
|
|
50
|
-
|
|
51
|
-
/**
|
|
52
|
-
* Location reference (for subject namespacing)
|
|
53
|
-
*/
|
|
54
|
-
locationRef: string;
|
|
55
|
-
|
|
56
|
-
/**
|
|
57
|
-
* ERP type (epicor, infor, etc.)
|
|
58
|
-
*/
|
|
59
|
-
erpType: string;
|
|
60
|
-
|
|
61
|
-
/**
|
|
62
|
-
* Enable/disable NATS
|
|
63
|
-
*/
|
|
64
|
-
enabled: boolean;
|
|
65
|
-
|
|
66
|
-
/**
|
|
67
|
-
* Auto-reconnect settings
|
|
68
|
-
*/
|
|
69
|
-
reconnect?: boolean;
|
|
70
|
-
maxReconnectAttempts?: number;
|
|
71
|
-
reconnectTimeWait?: number;
|
|
72
|
-
}
|
|
73
|
-
|
|
74
|
-
export class NatsService {
|
|
75
|
-
private connection: NatsConnection | null = null;
|
|
76
|
-
private subscriptions: Map<string, Subscription> = new Map();
|
|
77
|
-
private config: NatsServiceConfig;
|
|
78
|
-
private handlers: NatsHandlerRegistration[] = [];
|
|
79
|
-
private statusPublishTimer: NodeJS.Timeout | null = null;
|
|
80
|
-
|
|
81
|
-
constructor(config: NatsServiceConfig) {
|
|
82
|
-
this.config = config;
|
|
83
|
-
}
|
|
84
|
-
|
|
85
|
-
/**
|
|
86
|
-
* Register a handler for a specific subject pattern
|
|
87
|
-
*/
|
|
88
|
-
registerHandler(registration: NatsHandlerRegistration): void {
|
|
89
|
-
logger.info("Registering NATS handler", {
|
|
90
|
-
subject: registration.subject,
|
|
91
|
-
description: registration.description,
|
|
92
|
-
});
|
|
93
|
-
this.handlers.push(registration);
|
|
94
|
-
}
|
|
95
|
-
|
|
96
|
-
/**
|
|
97
|
-
* Connect to NATS and start all registered handlers
|
|
98
|
-
*/
|
|
99
|
-
async connect(): Promise<void> {
|
|
100
|
-
if (!this.config.enabled) {
|
|
101
|
-
logger.info("NATS is disabled, skipping connection");
|
|
102
|
-
return;
|
|
103
|
-
}
|
|
104
|
-
|
|
105
|
-
try {
|
|
106
|
-
logger.info("Connecting to NATS...", {
|
|
107
|
-
servers: this.config.servers,
|
|
108
|
-
name: this.config.name,
|
|
109
|
-
});
|
|
110
|
-
|
|
111
|
-
this.connection = await connect({
|
|
112
|
-
servers: this.config.servers,
|
|
113
|
-
name: this.config.name,
|
|
114
|
-
reconnect: this.config.reconnect ?? true,
|
|
115
|
-
maxReconnectAttempts: this.config.maxReconnectAttempts ?? -1,
|
|
116
|
-
reconnectTimeWait: this.config.reconnectTimeWait ?? 2000,
|
|
117
|
-
});
|
|
118
|
-
|
|
119
|
-
logger.info("Connected to NATS", {
|
|
120
|
-
server: this.connection.getServer(),
|
|
121
|
-
clientId: this.connection.info?.client_id,
|
|
122
|
-
});
|
|
123
|
-
|
|
124
|
-
// Start all registered handlers
|
|
125
|
-
for (const registration of this.handlers) {
|
|
126
|
-
await this.startHandler(registration);
|
|
127
|
-
}
|
|
128
|
-
|
|
129
|
-
// Start automatic status publishing
|
|
130
|
-
this.startStatusPublishing();
|
|
131
|
-
|
|
132
|
-
// Monitor connection status
|
|
133
|
-
this.monitorConnection();
|
|
134
|
-
|
|
135
|
-
// Graceful shutdown
|
|
136
|
-
this.setupShutdown();
|
|
137
|
-
} catch (error) {
|
|
138
|
-
logger.error("Failed to connect to NATS", { error });
|
|
139
|
-
throw error;
|
|
140
|
-
}
|
|
141
|
-
}
|
|
142
|
-
|
|
143
|
-
/**
|
|
144
|
-
* Start a single handler (subscribe to its subject)
|
|
145
|
-
*/
|
|
146
|
-
private async startHandler(registration: NatsHandlerRegistration): Promise<void> {
|
|
147
|
-
if (!this.connection) {
|
|
148
|
-
throw new Error("NATS connection not established");
|
|
149
|
-
}
|
|
150
|
-
|
|
151
|
-
const sub = this.connection.subscribe(registration.subject);
|
|
152
|
-
this.subscriptions.set(registration.subject, sub);
|
|
153
|
-
|
|
154
|
-
logger.info("Started NATS handler", {
|
|
155
|
-
subject: registration.subject,
|
|
156
|
-
description: registration.description,
|
|
157
|
-
});
|
|
158
|
-
|
|
159
|
-
// Process messages
|
|
160
|
-
(async () => {
|
|
161
|
-
for await (const msg of sub) {
|
|
162
|
-
try {
|
|
163
|
-
const data = sc.decode(msg.data);
|
|
164
|
-
|
|
165
|
-
logger.info("Received NATS message", {
|
|
166
|
-
subject: msg.subject,
|
|
167
|
-
hasReply: !!msg.reply,
|
|
168
|
-
});
|
|
169
|
-
|
|
170
|
-
// Parse JSON if possible
|
|
171
|
-
let parsedData: any;
|
|
172
|
-
try {
|
|
173
|
-
parsedData = JSON.parse(data);
|
|
174
|
-
} catch {
|
|
175
|
-
parsedData = data;
|
|
176
|
-
}
|
|
177
|
-
|
|
178
|
-
// Call handler
|
|
179
|
-
const response = await registration.handler.handle(parsedData, msg.subject);
|
|
180
|
-
|
|
181
|
-
// If there's a reply subject and handler returned something, reply
|
|
182
|
-
if (msg.reply && response !== undefined) {
|
|
183
|
-
const responseStr = JSON.stringify(response);
|
|
184
|
-
msg.respond(sc.encode(responseStr));
|
|
185
|
-
logger.info("Sent reply", { replySubject: msg.reply });
|
|
186
|
-
}
|
|
187
|
-
} catch (error) {
|
|
188
|
-
logger.error("Error handling NATS message", {
|
|
189
|
-
subject: msg.subject,
|
|
190
|
-
error,
|
|
191
|
-
});
|
|
192
|
-
|
|
193
|
-
// Send error response if reply expected
|
|
194
|
-
if (msg.reply) {
|
|
195
|
-
const errorResponse = {
|
|
196
|
-
status: "error",
|
|
197
|
-
error: {
|
|
198
|
-
message: error instanceof Error ? error.message : "Unknown error",
|
|
199
|
-
code: "HANDLER_ERROR",
|
|
200
|
-
},
|
|
201
|
-
};
|
|
202
|
-
msg.respond(sc.encode(JSON.stringify(errorResponse)));
|
|
203
|
-
}
|
|
204
|
-
}
|
|
205
|
-
}
|
|
206
|
-
})();
|
|
207
|
-
}
|
|
208
|
-
|
|
209
|
-
/**
|
|
210
|
-
* Publish a message to a subject (for pub/sub)
|
|
211
|
-
*/
|
|
212
|
-
async publish(subject: string, data: any): Promise<void> {
|
|
213
|
-
if (!this.connection) {
|
|
214
|
-
throw new Error("NATS connection not established");
|
|
215
|
-
}
|
|
216
|
-
|
|
217
|
-
const message = typeof data === "string" ? data : JSON.stringify(data);
|
|
218
|
-
this.connection.publish(subject, sc.encode(message));
|
|
219
|
-
|
|
220
|
-
logger.info("Published NATS message", { subject });
|
|
221
|
-
}
|
|
222
|
-
|
|
223
|
-
/**
|
|
224
|
-
* Send a request and wait for reply (for request-reply)
|
|
225
|
-
*/
|
|
226
|
-
async request(subject: string, data: any, timeoutMs: number = 30000): Promise<any> {
|
|
227
|
-
if (!this.connection) {
|
|
228
|
-
throw new Error("NATS connection not established");
|
|
229
|
-
}
|
|
230
|
-
|
|
231
|
-
const message = typeof data === "string" ? data : JSON.stringify(data);
|
|
232
|
-
const response = await this.connection.request(
|
|
233
|
-
subject,
|
|
234
|
-
sc.encode(message),
|
|
235
|
-
{ timeout: timeoutMs }
|
|
236
|
-
);
|
|
237
|
-
|
|
238
|
-
const responseData = sc.decode(response.data);
|
|
239
|
-
|
|
240
|
-
try {
|
|
241
|
-
return JSON.parse(responseData);
|
|
242
|
-
} catch {
|
|
243
|
-
return responseData;
|
|
244
|
-
}
|
|
245
|
-
}
|
|
246
|
-
|
|
247
|
-
/**
|
|
248
|
-
* Check if connected to NATS
|
|
249
|
-
*/
|
|
250
|
-
isConnected(): boolean {
|
|
251
|
-
return this.connection !== null && !this.connection.isClosed();
|
|
252
|
-
}
|
|
253
|
-
|
|
254
|
-
/**
|
|
255
|
-
* Start automatic status publishing (every 30 seconds)
|
|
256
|
-
*/
|
|
257
|
-
private startStatusPublishing(): void {
|
|
258
|
-
logger.info("Starting status publishing (every 30 seconds)");
|
|
259
|
-
|
|
260
|
-
// Publish immediately on start
|
|
261
|
-
this.publishStatus();
|
|
262
|
-
|
|
263
|
-
// Then publish every 30 seconds
|
|
264
|
-
this.statusPublishTimer = setInterval(() => {
|
|
265
|
-
this.publishStatus();
|
|
266
|
-
}, 30000);
|
|
267
|
-
}
|
|
268
|
-
|
|
269
|
-
/**
|
|
270
|
-
* Publish connector status
|
|
271
|
-
*/
|
|
272
|
-
private async publishStatus(): Promise<void> {
|
|
273
|
-
try {
|
|
274
|
-
const status = {
|
|
275
|
-
timestamp: new Date().toISOString(),
|
|
276
|
-
locationRef: this.config.locationRef,
|
|
277
|
-
erpType: this.config.erpType,
|
|
278
|
-
natsConnected: this.isConnected(),
|
|
279
|
-
};
|
|
280
|
-
|
|
281
|
-
await this.publish(
|
|
282
|
-
`mm.14.${this.config.locationRef}.erp.status`,
|
|
283
|
-
status
|
|
284
|
-
);
|
|
285
|
-
|
|
286
|
-
logger.debug("Published connector status");
|
|
287
|
-
} catch (error) {
|
|
288
|
-
logger.error("Failed to publish status", { error });
|
|
289
|
-
}
|
|
290
|
-
}
|
|
291
|
-
|
|
292
|
-
/**
|
|
293
|
-
* Monitor connection status
|
|
294
|
-
*/
|
|
295
|
-
private monitorConnection(): void {
|
|
296
|
-
if (!this.connection) return;
|
|
297
|
-
|
|
298
|
-
(async () => {
|
|
299
|
-
for await (const status of this.connection!.status()) {
|
|
300
|
-
// Only log important events, skip pingTimer
|
|
301
|
-
if (status.type !== "pingTimer") {
|
|
302
|
-
logger.info("NATS connection status", {
|
|
303
|
-
type: status.type,
|
|
304
|
-
data: status.data,
|
|
305
|
-
});
|
|
306
|
-
}
|
|
307
|
-
}
|
|
308
|
-
})();
|
|
309
|
-
}
|
|
310
|
-
|
|
311
|
-
/**
|
|
312
|
-
* Setup graceful shutdown
|
|
313
|
-
*/
|
|
314
|
-
private setupShutdown(): void {
|
|
315
|
-
const shutdown = async () => {
|
|
316
|
-
logger.info("Shutting down NATS service...");
|
|
317
|
-
await this.disconnect();
|
|
318
|
-
process.exit(0);
|
|
319
|
-
};
|
|
320
|
-
|
|
321
|
-
process.on("SIGINT", shutdown);
|
|
322
|
-
process.on("SIGTERM", shutdown);
|
|
323
|
-
}
|
|
324
|
-
|
|
325
|
-
/**
|
|
326
|
-
* Disconnect from NATS
|
|
327
|
-
*/
|
|
328
|
-
async disconnect(): Promise<void> {
|
|
329
|
-
// Stop status publishing
|
|
330
|
-
if (this.statusPublishTimer) {
|
|
331
|
-
clearInterval(this.statusPublishTimer);
|
|
332
|
-
this.statusPublishTimer = null;
|
|
333
|
-
}
|
|
334
|
-
|
|
335
|
-
// Close connection
|
|
336
|
-
if (this.connection) {
|
|
337
|
-
await this.connection.drain();
|
|
338
|
-
this.connection = null;
|
|
339
|
-
this.subscriptions.clear();
|
|
340
|
-
logger.info("Disconnected from NATS");
|
|
341
|
-
}
|
|
342
|
-
}
|
|
343
|
-
|
|
344
|
-
/**
|
|
345
|
-
* Get the location reference
|
|
346
|
-
*/
|
|
347
|
-
getLocationRef(): string {
|
|
348
|
-
return this.config.locationRef;
|
|
349
|
-
}
|
|
350
|
-
}
|
|
351
|
-
|
|
@@ -1,96 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Simple proof-of-concept NATS subscriber
|
|
3
|
-
* Subscribes to mm.14.> and replies with "hello world"
|
|
4
|
-
*/
|
|
5
|
-
|
|
6
|
-
import { connect, StringCodec } from "nats";
|
|
7
|
-
import { logger } from "../../services/reporting-service";
|
|
8
|
-
|
|
9
|
-
const sc = StringCodec();
|
|
10
|
-
|
|
11
|
-
async function startTestSubscriber() {
|
|
12
|
-
try {
|
|
13
|
-
// Connect to NATS server
|
|
14
|
-
const nc = await connect({
|
|
15
|
-
servers: "nats://localhost:4222",
|
|
16
|
-
name: "mm-erp-sdk-test-subscriber",
|
|
17
|
-
});
|
|
18
|
-
|
|
19
|
-
logger.info("Connected to NATS server", {
|
|
20
|
-
server: nc.getServer(),
|
|
21
|
-
clientId: nc.info?.client_id,
|
|
22
|
-
});
|
|
23
|
-
|
|
24
|
-
// Subscribe to all messages on mm.14.>
|
|
25
|
-
const sub = nc.subscribe("mm.14.>");
|
|
26
|
-
|
|
27
|
-
logger.info("Subscribed to mm.14.> - waiting for messages...");
|
|
28
|
-
|
|
29
|
-
// Process incoming messages
|
|
30
|
-
(async () => {
|
|
31
|
-
for await (const msg of sub) {
|
|
32
|
-
const data = sc.decode(msg.data);
|
|
33
|
-
|
|
34
|
-
logger.info("📨 Received NATS message", {
|
|
35
|
-
subject: msg.subject,
|
|
36
|
-
data: data,
|
|
37
|
-
reply: msg.reply,
|
|
38
|
-
});
|
|
39
|
-
|
|
40
|
-
console.log("\n=== NATS MESSAGE RECEIVED ===");
|
|
41
|
-
console.log("Subject:", msg.subject);
|
|
42
|
-
console.log("Data:", data);
|
|
43
|
-
console.log("Reply subject:", msg.reply);
|
|
44
|
-
console.log("============================\n");
|
|
45
|
-
|
|
46
|
-
// Reply if there's a reply subject
|
|
47
|
-
if (msg.reply) {
|
|
48
|
-
const replyMessage = JSON.stringify({
|
|
49
|
-
message: "hello world",
|
|
50
|
-
timestamp: new Date().toISOString(),
|
|
51
|
-
receivedSubject: msg.subject,
|
|
52
|
-
receivedData: data,
|
|
53
|
-
});
|
|
54
|
-
|
|
55
|
-
msg.respond(sc.encode(replyMessage));
|
|
56
|
-
|
|
57
|
-
logger.info("✅ Sent reply: hello world", {
|
|
58
|
-
replySubject: msg.reply,
|
|
59
|
-
});
|
|
60
|
-
|
|
61
|
-
console.log("✅ Replied with: hello world\n");
|
|
62
|
-
}
|
|
63
|
-
}
|
|
64
|
-
})();
|
|
65
|
-
|
|
66
|
-
// Handle connection events
|
|
67
|
-
(async () => {
|
|
68
|
-
for await (const status of nc.status()) {
|
|
69
|
-
logger.info("NATS connection status", {
|
|
70
|
-
type: status.type,
|
|
71
|
-
data: status.data,
|
|
72
|
-
});
|
|
73
|
-
console.log(`Connection status: ${status.type}`, status.data);
|
|
74
|
-
}
|
|
75
|
-
})();
|
|
76
|
-
|
|
77
|
-
// Graceful shutdown
|
|
78
|
-
const shutdown = async () => {
|
|
79
|
-
logger.info("Shutting down NATS subscriber...");
|
|
80
|
-
await nc.drain();
|
|
81
|
-
process.exit(0);
|
|
82
|
-
};
|
|
83
|
-
|
|
84
|
-
process.on("SIGINT", shutdown);
|
|
85
|
-
process.on("SIGTERM", shutdown);
|
|
86
|
-
|
|
87
|
-
} catch (error) {
|
|
88
|
-
logger.error("Failed to connect to NATS", { error });
|
|
89
|
-
console.error("Error connecting to NATS:", error);
|
|
90
|
-
process.exit(1);
|
|
91
|
-
}
|
|
92
|
-
}
|
|
93
|
-
|
|
94
|
-
// Start the subscriber
|
|
95
|
-
startTestSubscriber();
|
|
96
|
-
|
|
@@ -1,205 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Error formatter utility for standardizing error messages across connectors
|
|
3
|
-
* Extracts human-readable messages from various error types (axios, custom errors, etc.)
|
|
4
|
-
*/
|
|
5
|
-
|
|
6
|
-
export interface FormattedError {
|
|
7
|
-
message: string;
|
|
8
|
-
code: string;
|
|
9
|
-
httpStatus?: number;
|
|
10
|
-
metadata?: Record<string, any>;
|
|
11
|
-
}
|
|
12
|
-
|
|
13
|
-
/**
|
|
14
|
-
* Extract meaningful error message from various error types
|
|
15
|
-
*/
|
|
16
|
-
export function formatError(error: any): FormattedError {
|
|
17
|
-
if (!error) {
|
|
18
|
-
return {
|
|
19
|
-
message: 'Unknown error occurred',
|
|
20
|
-
code: 'UNKNOWN_ERROR',
|
|
21
|
-
};
|
|
22
|
-
}
|
|
23
|
-
|
|
24
|
-
// Handle axios errors FIRST (before checking for FormattedError)
|
|
25
|
-
// because axios errors also have message and code properties
|
|
26
|
-
if (error.isAxiosError || error.name === 'AxiosError') {
|
|
27
|
-
return formatAxiosError(error);
|
|
28
|
-
}
|
|
29
|
-
|
|
30
|
-
// If it's already a FormattedError, return as-is
|
|
31
|
-
// Check for httpStatus or metadata to distinguish from axios errors
|
|
32
|
-
if (error.message && error.code && typeof error.message === 'string' && typeof error.code === 'string' && !error.config) {
|
|
33
|
-
return error as FormattedError;
|
|
34
|
-
}
|
|
35
|
-
|
|
36
|
-
// Handle standard Error objects
|
|
37
|
-
if (error instanceof Error) {
|
|
38
|
-
return {
|
|
39
|
-
message: error.message || 'An error occurred',
|
|
40
|
-
code: 'ERROR',
|
|
41
|
-
metadata: {
|
|
42
|
-
name: error.name,
|
|
43
|
-
},
|
|
44
|
-
};
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
// Handle string errors
|
|
48
|
-
if (typeof error === 'string') {
|
|
49
|
-
return {
|
|
50
|
-
message: error,
|
|
51
|
-
code: 'ERROR',
|
|
52
|
-
};
|
|
53
|
-
}
|
|
54
|
-
|
|
55
|
-
// Last resort: try to extract any useful info
|
|
56
|
-
const message = error.message || error.toString?.() || 'Unknown error occurred';
|
|
57
|
-
return {
|
|
58
|
-
message: typeof message === 'string' ? message : JSON.stringify(message),
|
|
59
|
-
code: error.code || 'UNKNOWN_ERROR',
|
|
60
|
-
};
|
|
61
|
-
}
|
|
62
|
-
|
|
63
|
-
/**
|
|
64
|
-
* Format axios-specific errors with detailed context
|
|
65
|
-
*/
|
|
66
|
-
function formatAxiosError(error: any): FormattedError {
|
|
67
|
-
const httpStatus = error.response?.status;
|
|
68
|
-
const method = error.config?.method?.toUpperCase();
|
|
69
|
-
const url = error.config?.url;
|
|
70
|
-
|
|
71
|
-
// First check if connector already extracted the message
|
|
72
|
-
let message = error._extractedMessage;
|
|
73
|
-
|
|
74
|
-
// If not, try to extract from response data
|
|
75
|
-
if (!message) {
|
|
76
|
-
const extractedMessage = extractErrorMessage(error.response?.data);
|
|
77
|
-
message = extractedMessage || error.response?.statusText || error.message || 'Request failed';
|
|
78
|
-
}
|
|
79
|
-
|
|
80
|
-
// Determine error code based on status
|
|
81
|
-
const code = categorizeHttpError(httpStatus);
|
|
82
|
-
|
|
83
|
-
const metadata: Record<string, any> = {
|
|
84
|
-
method,
|
|
85
|
-
url,
|
|
86
|
-
};
|
|
87
|
-
|
|
88
|
-
// Add additional context for specific error types
|
|
89
|
-
if (httpStatus === 401 || httpStatus === 403) {
|
|
90
|
-
metadata.hint = 'Check authentication credentials';
|
|
91
|
-
} else if (httpStatus === 404) {
|
|
92
|
-
metadata.hint = 'Resource not found - check endpoint URL';
|
|
93
|
-
} else if (httpStatus && httpStatus >= 500) {
|
|
94
|
-
metadata.hint = 'ERP system may be temporarily unavailable';
|
|
95
|
-
}
|
|
96
|
-
|
|
97
|
-
return {
|
|
98
|
-
message,
|
|
99
|
-
code,
|
|
100
|
-
httpStatus,
|
|
101
|
-
metadata,
|
|
102
|
-
};
|
|
103
|
-
}
|
|
104
|
-
|
|
105
|
-
/**
|
|
106
|
-
* Extract meaningful error message from response data
|
|
107
|
-
* Handles various ERP-specific response formats
|
|
108
|
-
*/
|
|
109
|
-
function extractErrorMessage(data: any): string | null {
|
|
110
|
-
if (!data) return null;
|
|
111
|
-
|
|
112
|
-
// Common error message fields across different ERPs
|
|
113
|
-
const possibleFields = [
|
|
114
|
-
'ErrorMessage', // Epicor
|
|
115
|
-
'error.message', // Common REST format
|
|
116
|
-
'error', // Simple format
|
|
117
|
-
'Message', // .NET style
|
|
118
|
-
'message', // JavaScript style
|
|
119
|
-
'errorMessage', // Camel case
|
|
120
|
-
'error_message', // Snake case
|
|
121
|
-
'errors[0].message', // Array of errors
|
|
122
|
-
'title', // Problem details format
|
|
123
|
-
'detail', // Problem details format
|
|
124
|
-
];
|
|
125
|
-
|
|
126
|
-
for (const field of possibleFields) {
|
|
127
|
-
const value = getNestedValue(data, field);
|
|
128
|
-
if (value && typeof value === 'string') {
|
|
129
|
-
return value;
|
|
130
|
-
}
|
|
131
|
-
}
|
|
132
|
-
|
|
133
|
-
// If data is a string, return it
|
|
134
|
-
if (typeof data === 'string') {
|
|
135
|
-
// Try to parse as JSON first
|
|
136
|
-
try {
|
|
137
|
-
const parsed = JSON.parse(data);
|
|
138
|
-
return extractErrorMessage(parsed);
|
|
139
|
-
} catch {
|
|
140
|
-
return data;
|
|
141
|
-
}
|
|
142
|
-
}
|
|
143
|
-
|
|
144
|
-
return null;
|
|
145
|
-
}
|
|
146
|
-
|
|
147
|
-
/**
|
|
148
|
-
* Get nested value from object using dot notation
|
|
149
|
-
*/
|
|
150
|
-
function getNestedValue(obj: any, path: string): any {
|
|
151
|
-
const parts = path.split('.');
|
|
152
|
-
let current = obj;
|
|
153
|
-
|
|
154
|
-
for (const part of parts) {
|
|
155
|
-
// Handle array notation like 'errors[0]'
|
|
156
|
-
const arrayMatch = part.match(/(\w+)\[(\d+)\]/);
|
|
157
|
-
if (arrayMatch) {
|
|
158
|
-
const [, key, index] = arrayMatch;
|
|
159
|
-
current = current?.[key]?.[parseInt(index, 10)];
|
|
160
|
-
} else {
|
|
161
|
-
current = current?.[part];
|
|
162
|
-
}
|
|
163
|
-
|
|
164
|
-
if (current === undefined || current === null) {
|
|
165
|
-
return null;
|
|
166
|
-
}
|
|
167
|
-
}
|
|
168
|
-
|
|
169
|
-
return current;
|
|
170
|
-
}
|
|
171
|
-
|
|
172
|
-
/**
|
|
173
|
-
* Categorize HTTP errors into standard codes
|
|
174
|
-
*/
|
|
175
|
-
function categorizeHttpError(status?: number): string {
|
|
176
|
-
if (!status) return 'NETWORK_ERROR';
|
|
177
|
-
|
|
178
|
-
if (status === 400) return 'VALIDATION_ERROR';
|
|
179
|
-
if (status === 401) return 'AUTHENTICATION_ERROR';
|
|
180
|
-
if (status === 403) return 'AUTHORIZATION_ERROR';
|
|
181
|
-
if (status === 404) return 'NOT_FOUND';
|
|
182
|
-
if (status === 409) return 'CONFLICT';
|
|
183
|
-
if (status === 422) return 'VALIDATION_ERROR';
|
|
184
|
-
if (status === 429) return 'RATE_LIMIT';
|
|
185
|
-
if (status >= 500) return 'ERP_SERVER_ERROR';
|
|
186
|
-
if (status >= 400) return 'CLIENT_ERROR';
|
|
187
|
-
|
|
188
|
-
return 'HTTP_ERROR';
|
|
189
|
-
}
|
|
190
|
-
|
|
191
|
-
/**
|
|
192
|
-
* Format error for logging (shorter, cleaner version)
|
|
193
|
-
*/
|
|
194
|
-
export function formatErrorForLogging(error: any): string {
|
|
195
|
-
const formatted = formatError(error);
|
|
196
|
-
|
|
197
|
-
let message = `[${formatted.code}] ${formatted.message}`;
|
|
198
|
-
|
|
199
|
-
if (formatted.httpStatus) {
|
|
200
|
-
message = `[${formatted.httpStatus}] ${message}`;
|
|
201
|
-
}
|
|
202
|
-
|
|
203
|
-
return message;
|
|
204
|
-
}
|
|
205
|
-
|