-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
1163 lines (1053 loc) · 35.6 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import type { z } from "zod";
import { apiCall } from "./api";
import { generateWaybillPDF } from "./api/custom-waybill.server";
import { generateWaybillsPDF } from "./api/custom-waybills.server";
import type { NinjaWebhookEvent, NinjaWebhookEventType } from "./api/webhooks";
import {
isNinjaWebhookEventType,
verifyNinjaWebhookSignature,
} from "./api/webhooks";
import type {
CreateOrderInput,
CustomWaybillInput,
WrapperArgsInput,
} from "./schemas";
import {
TrackOrder,
TrackOrderNinjaResponse,
TrackOrders,
TrackOrdersNinjaResponse,
CancelOrder,
CancelOrderNinjaResponse,
CreateOrder,
CreateOrderNinjaResponse,
GenerateWaybill,
GenerateWaybillNinjaResponse,
GetToken,
GetTokenNinjaResponse,
validWrapperArgs,
} from "./schemas";
import type { Mock } from "./types";
import {
capitalize,
getNinjaBufferPathFromCache,
getNinjaTokenFromCache,
jsonParse,
logger as pinoLogger,
logsMessages as ms,
upsertNinjaBufferIntoCache,
upsertNinjaTokenIntoCache,
} from "./utils";
/**
* @description - A Wrapper around ninjavan `API`s
*/
function ninjavan(args: WrapperArgsInput, mock?: Mock, logger?: boolean) {
/** 1. initialize conditional logger */
const _logger = pinoLogger(logger);
const info = (log: string, child?: object) =>
_logger.child(child ?? {}).info(log);
const error = (log: string, child?: object) =>
_logger.child(child ?? {}).error(log);
/** 2. validate wrapper args */
// logs
info(ms.initializingWrapper, { args, mock });
// runtime validation
info(ms.validatingWrapperArgs);
const _args = validWrapperArgs(args);
if (typeof _args === "string") {
error(ms.invalidWrapperArgs, { error: _args });
throw new Error(ms.invalidWrapperArgs + " " + _args);
}
info(ms.validWrapperArgs, { args: _args });
// spread args
const { clientId, clientSecret, baseUrl, countryCode } = _args;
info(ms.initializedWrapper);
/** 3. initialize wrapper dependencies */
/**
* @see https://api-docs.ninjavan.co/en#tag/OAuth-API
*
* @description - gets a valid ninjavan token from their api if it's not already cached
*/
async function getToken() {
info(ms.runGetToken);
// prepare dependencies
const url = `${baseUrl}/${countryCode}/2.0/oauth/access_token`;
const key = `${baseUrl}/${countryCode}?client_id=${clientId}`;
// handle mock
if (mock) return handleMock(mock, "get.token", { key, url }) as string;
// get token
// from cache
info(ms.gettingToken, { key, url });
const cachedToken = await getNinjaTokenFromCache(key);
if (cachedToken) {
info(ms.tokenFromCache, { token: cachedToken });
return cachedToken;
}
info(ms.tokenNotInCache, { key, url });
// from api
try {
const data = (
await apiCall(
GetToken,
GetTokenNinjaResponse,
{
url,
input: {
client_id: clientId,
client_secret: clientSecret,
},
},
(args) =>
fetch(args.url, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(args.input),
}),
info,
error
)
)(GetTokenNinjaResponse);
const authHeaderValue = `${capitalize(data.token_type)} ${
data.access_token
}`;
const cachingResponse = await upsertNinjaTokenIntoCache(key, {
token: data.access_token,
tokenType: capitalize(data.token_type),
expiresIn: data.expires_in,
});
if (cachingResponse) {
info(ms.tokenCached, { key, url, value: authHeaderValue });
} else {
error(ms.tokenNotCached, { key, url, value: authHeaderValue });
console.log(`❌ token caching failed, figure this out`);
}
return authHeaderValue;
} catch (err) {
// extra report to close getToken() logs
error(ms.getTokenError, { error: (err as Error).message });
throw error;
}
}
/** 4. return wrapper's public API */
const methods = {
/**
*
* @param {CreateOrderInput["input"]} args - the input args for ninja
* create order api
* @param {string} token - if you want to provide the token yourself
* @returns - the response of ninja create order api
*/
async createOrder(args: CreateOrderInput["input"], token?: string) {
info(ms.runCreateOrder);
// prepare dependencies
const url = `${baseUrl}/${countryCode}/4.0/orders`;
const _token = token ?? ((await getToken()) as string);
// handle mock
if (mock)
return handleMock(mock, "create.order", {
url,
token: _token,
args,
}) as z.infer<typeof CreateOrderNinjaResponse>;
// call api
try {
const data = (
await apiCall(
CreateOrder,
CreateOrderNinjaResponse,
{
url,
input: args,
},
(args) =>
fetch(args.url, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: _token,
},
body: JSON.stringify(args.input),
}),
info,
error
)
)(CreateOrderNinjaResponse);
return data;
} catch (err) {
// extra report to close createOrder() logs
error(ms.createOrderError, { error: (err as Error).message });
throw err;
}
},
/**
*
* @param args - array of the input args for ninja create order api
* @param token - if you want to provide the token yourself
* @param logger - if true, this function will use its own logger
* instead of the wrapper's logger, so you can disable the wrapper's
* logger focus on this function's logs. @default false
* @param strict - if true, the function either create all orders or
* none, this happens by cancelling all successful orders if one
* failed, if cancelation fails, you should get a response that tells
* you what to do. @default false
*
* @description - this function is a parallel version of many createOrder()
* calls, it generates its own token for a better performance
* @returns
*/
async createOrders(
args: Array<CreateOrderInput["input"]>,
token?: string,
_logger?: boolean,
strict?: boolean
) {
if (typeof strict === "undefined") strict = false;
// prepare logger
const loggerEnabled = _logger ?? logger ?? false;
const __logger = pinoLogger(loggerEnabled);
const _info = (log: string, child?: object) =>
__logger.child(child ?? {}).info(log);
const _error = (log: string, child?: object) =>
__logger.child(child ?? {}).error(log);
_info(ms.runCreateOrders);
/** 0. get token */
_info(ms.gettingToken);
const _token = token ?? ((await getToken()) as string);
// ^^^^ this will throw an error if it fails, b ready 2 catchit
/** 1. create all orders */
_info(ms.creatingOrders, { total: args.length, strict });
// prepare promises
const promises = args.map((x) => methods.createOrder(x, _token));
// wait for all promises to settle
const r = await Promise.allSettled(promises);
// check if any failed
const hasFailed = r.some((x) => x.status === "rejected");
// no failed orders
if (!hasFailed) {
_info(ms.allOrdersCreated, { total: r.length });
// return all fulfilled orders, as part of stats
return {
ok: true,
stats: {
total: r.length,
success: r.length,
failed: 0,
},
// this filter for types inference
data: r.filter(isFulfilled).map((x) => x.value),
error: null,
cancelation: undefined,
};
}
/** 2. has some failed orders */
_error(ms.someOrdersFailed, {
total: r.length,
failed: r.filter(isRejected).length,
});
// if strict is false, we return all orders, as part of stats
// with errors' details
if (!strict) {
return {
ok: false,
stats: {
total: r.length,
success: r.filter(isFulfilled).length,
failed: r.filter(isRejected).length,
},
data: r.filter(isFulfilled).map((x) => x.value),
error: r.filter(isRejected).map((x) => getErrorMessage(x.reason)),
cancelation: undefined,
};
}
/** 3. reverse orders creation */
// strict is `true` and there are failed orders, we cancel
// start cancelling all successful orders
// extract tracking numbers
const successfulOrders = r.filter(isFulfilled).map((x) => x.value);
const idsToCancel = successfulOrders.map((x) => x.tracking_number);
// reverse create orders
const cancelation = await methods.cancelOrders(
idsToCancel,
_token,
loggerEnabled
);
return {
ok: false,
stats: {
total: r.length,
success: r.filter(isFulfilled).length,
failed: r.filter(isRejected).length,
},
data: r.filter(isFulfilled).map((x) => x.value),
error: r.filter(isRejected).map((x) => getErrorMessage(x.reason)),
cancelation: {
...cancelation,
},
};
},
/**
*
* @param args - the input args for ninja cancel order api
* @param {string} token - if you want to provide the token yourself
* @returns - the response of ninja cancel order api
*/
async cancelOrder(args: { trackingNumber: string }, token?: string) {
info(ms.runCancelOrder);
// prepare dependencies
const url = `${baseUrl}/${countryCode}/2.2/orders/${args.trackingNumber}`;
const _token = token ?? ((await getToken()) as string);
// handle mock
if (mock)
return handleMock(mock, "cancel.order", {
url,
token: _token,
args,
}) satisfies any;
// call api
try {
const data = (
await apiCall(
CancelOrder,
CancelOrderNinjaResponse,
{
url,
},
(args) =>
fetch(args.url, {
method: "DELETE",
headers: {
"Content-Type": "application/json",
Authorization: _token,
},
}),
info,
error
)
)(CancelOrderNinjaResponse);
return data;
} catch (err) {
// extra report to close cancelOrder() logs
error(ms.cancelOrderError, { error: (err as Error).message });
throw err;
}
},
/**
*
* @param args - array of ids to cancel
* @param logger - if true, this function will use its own logger
* instead of the wrapper's logger, so you can disable the wrapper's
* logger focus on this function's logs. @default false
* @returns
* @description - this function is a parallel version of many cancelOrder()
* calls, it generates its own token for a better performance
* @returns
*/
async cancelOrders(args: string[], token?: string, _logger?: boolean) {
// prepare logger
const loggerEnabled = _logger ?? logger ?? false;
const __logger = pinoLogger(loggerEnabled);
const _info = (log: string, child?: object) =>
__logger.child(child ?? {}).info(log);
const _error = (log: string, child?: object) =>
__logger.child(child ?? {}).error(log);
_info(ms.runCancelOrders);
// prepare dependencies
const _token = token ?? ((await getToken()) as string);
// prepare canceling promises
const cancelPromises = args.map((x) =>
methods.cancelOrder(
{
trackingNumber: x,
},
_token
)
);
// wait for all canceling promises to settle
_info(ms.cancelingSuccessfulOrders, {
total: args.length,
canceling: args,
});
const cancelResults = await Promise.allSettled(cancelPromises);
// check if any canceling failed
const hasCancelFailed = cancelResults.some(
(x) => x.status === "rejected"
);
// no failed canceling
if (!hasCancelFailed) {
_info(ms.allSuccessfulOrdersCanceled, { total: cancelResults.length });
return {
ok: true,
stats: {
total: cancelResults.length,
success: cancelResults.length,
failed: 0,
},
data: cancelResults.filter(isFulfilled).map((x) => x.value),
error: null,
};
}
_error(ms.someCancelationFailed, {
total: cancelResults.length,
failed: cancelResults.filter(isRejected).length,
});
// TODO: handle cancelation failed. i.e retry cancelation or something
// for now we'll just inform the user that some cancelation failed
return {
ok: false,
stats: {
total: cancelResults.length,
success: cancelResults.filter(isFulfilled).length,
failed: cancelResults.filter(isRejected).length,
},
// this filter for types inference
data: cancelResults.filter(isFulfilled).map((x) => x.value),
error: cancelResults
.filter(isRejected)
.map((x) => getErrorMessage(x.reason)),
};
},
/**
* @note You shouldn't call this api directly after creating an order
* @see https://api-docs.ninjavan.co/en#tag/Order-API/paths/~1%7BcountryCode%7D~12.0~1reports~1waybill/get
*
* @note - ninja's generate waybill api is rate limited, cache the response always
*
* @param trackingNumber - the tracking number of the order
* @param showShipperDetails - whether to show the shipper details or not
* @returns the response of ninja generate waybill api
*/
async generateWaybill(args: {
trackingNumber: string;
showShipperDetails?: boolean;
}) {
info(ms.runGenerateWaybill);
// prepare dependencies
const name = `waybill-${args.trackingNumber}`;
/**
* A flag for hiding shipper's details, such as contact information, on the waybill. If no flag is provided with the query, the details are hidden. To explicitly hide the details, set to 1. To show the details, set to 0.
*/
const h = args.showShipperDetails ? 0 : 1;
/**
* The tracking_number as generated by the Order API.
*/
const tids = args.trackingNumber;
const url = `${baseUrl}/${countryCode}/2.0/reports/waybill?h=${h}&tids=${tids}`;
const token = (await getToken()) as string;
// handle mock
if (mock)
return handleMock(mock, "generate.waybill", {
url,
token,
name,
args,
}) as z.infer<typeof GenerateWaybillNinjaResponse>;
// check cache
info(ms.gettingWaybill, { name, url });
const cachedAirwaybill = await getNinjaBufferPathFromCache(name);
if (cachedAirwaybill) {
info(ms.waybillFromCache, { waybill: cachedAirwaybill });
return cachedAirwaybill;
}
info(ms.waybillNotInCache, { name, url });
// call api
try {
const data = (
await apiCall(
GenerateWaybill,
GenerateWaybillNinjaResponse,
{
url,
},
(args) =>
fetch(args.url, {
method: "GET",
headers: {
"Content-Type": "application/pdf",
Authorization: token,
},
redirect: "follow",
}),
info,
error,
// ignore the output validation
true
)
)(GenerateWaybillNinjaResponse);
info(`
🔥 You can generate a waybill only for an order that is \n
successfully processed. After an order creation request \n
is accepted by the order creation endpoint, the order \n
goes into a queue for further processing. When it's fully \n
processed, the platform generates a Pending Pickup webhook \n
(see Sample webhook payloads). This webhook gives your \n
system an indication that a waybill can be generated.\n\n
🔕 So Basically this api returns nothing, if the order is\n
not yet processed.
`);
const cachingResponse = await upsertNinjaBufferIntoCache(
// bufferArray coming from parsing the response
data,
name
);
if (cachingResponse) {
info(ms.waybillCached, { value: cachingResponse });
} else {
error(ms.waybillNotCached, { value: cachingResponse });
console.log(`❌ waybill caching failed, figure this out`);
}
const _ = cachingResponse
? cachingResponse
: {
path: null,
buffer: Buffer.from(data),
};
return _;
} catch (err) {
// extra report to close generateWaybill() logs
error(ms.generateWaybillError, { error: (err as Error).message });
throw err;
}
},
/**
* - You shouldn't rely on this api to track orders, instead
* subscribe to ninjavan webhooks per event
*
* @returns the response of ninja api
*/
async trackOrder(args: { trackingNumber: string }) {
info(ms.runTrackOrder);
// prepare dependencies
const url = `${baseUrl}/${countryCode}/1.0/orders/tracking-events/${args.trackingNumber}`;
const token = (await getToken()) as string;
// handle mock
if (mock)
return handleMock(mock, "track.order", {
url,
args,
}) as z.infer<typeof TrackOrderNinjaResponse>;
// call api
try {
const data = (
await apiCall(
TrackOrder,
TrackOrderNinjaResponse,
{
url,
},
(args) =>
fetch(args.url, {
method: "GET",
headers: {
"Content-Type": "application/json",
Authorization: token,
},
}),
info,
error
)
)(TrackOrderNinjaResponse);
return data;
} catch (err) {
error(ms.trackOrderError, { error: (err as Error).message });
throw err;
}
},
/**
* - You shouldn't rely on this api to track orders, instead
* subscribe to ninjavan webhooks per event
*
* @returns the response of ninja api
*/
async trackOrders(args: { trackingNumbers: string[] }) {
info(ms.runTrackOrders);
// prepare dependencies
const _url = new URL(
`${baseUrl}/${countryCode}/1.0/orders/tracking-events`
);
// add tracking numbers to url as searchParams
args.trackingNumbers.forEach((trackingNumber) => {
_url.searchParams.append("tracking_number", trackingNumber);
});
const url = _url.toString();
const token = (await getToken()) as string;
// handle mock
if (mock)
return handleMock(mock, "track.orders", {
url,
args,
}) as z.infer<typeof TrackOrdersNinjaResponse>;
// call api
try {
const data = (
await apiCall(
TrackOrders,
TrackOrdersNinjaResponse,
{
url,
},
(args) =>
fetch(args.url, {
method: "GET",
headers: {
"Content-Type": "application/json",
Authorization: token,
},
}),
info,
error
)
)(TrackOrdersNinjaResponse);
return data;
} catch (err) {
error(ms.trackOrdersError, { error: (err as Error).message });
throw err;
}
},
/**
* we're using external api to generate the waybill
*
* @description generate a custom waybill for a single order
*
* @param args see CustomNinjaWaybillInput type
* @returns url: Path to the stored generated PDF
*/
async customWaybill(args: CustomWaybillInput) {
info(ms.runCustomWaybill);
return await generateWaybillPDF(args);
},
/**
* we're using external api to generate the waybill
*
* @description generate custom waybills for multiple orders
* be careful when using this function, you better cache the generated
* waybill path somewhere and use it instead of generating a new one
* every time you want to
*
* this function is limited to 100 waybills at a time by default
*
* @param args see CustomNinjaWaybillInput type
* @returns url: Path to the stored generated PDF
*/
async customWaybills(args: CustomWaybillInput[], limitless?: boolean) {
info(ms.runCustomWaybills);
const isLimitless = limitless ?? false;
if (!isLimitless && args.length > 100)
throw new Error(
"You can only generate 100 waybills at a time, use the limitless option to bypass this limit"
);
return await generateWaybillsPDF(args);
},
/**
* @note Webhook Strategy:
* Some apis, maybe ninjavan disable your webhook endpoint if
* it returns a non 200 status code more than `n` number of times,
* to solve this
* - You always return `200: success` from your webhook endpoint
* to NinjaVan [unless a fatal error occurs], if so it's better to
* get your webhook endpoint disabled than to miss an important
* event
* - You report normal errors to handle them later
* - You report fatal errors to handle them urgently
*
* @note Error Codes: <-- You can choose which error is fatal or not
* - Initialization Errors:
* - 9900: Invalid args (you should test this as part of the setup)
* - Signature Errors:
* - 9901: No signature header found
* - 9902: Invalid signature
* - Payload Errors:
* - 9903: No event type found
* - 9904: Not registered event type
* - 9905: Invalid event type
*
* @note How to use
* - it's all about how you initialize the wrapper
* in a multi-tenant app you can either create an endpoint for each
* tenant, or go more dynamic `example.com/webhook/:tenantId`, then
* your users can register the number of webhooks you require
* - @see how-to-use below the function
*
* @param args {
* request: Request, we use this to get the request body and headers
* }
* @param failureCallback - callback to run when the webhook fails
* usually to report fetal error
* @param successCallback - callback to run when the webhook succeeds
*
* @returns {
* event: string,
* payload: the original payload, [UNTYPED]
* }
*/
async receiveWebhook(
args: {
request: Request;
registeredEvents: Array<NinjaWebhookEventType | "*">;
},
failureCallback?: (
err: { code: number; message: string },
data?: { body: string | object } | object
) => void,
successCallback?: (data: {
event: NinjaWebhookEventType;
[index: string | number]: any;
}) => void
) {
info(ms.runReceiveWebhook);
const signatureHeaderName = "X-Ninjavan-Hmac-Sha256";
if (!successCallback) successCallback = () => undefined;
if (!failureCallback) failureCallback = () => undefined;
// 1. Extract information from the request
info(ms.extractingPayload);
const body = await args.request.text();
const signatureHeader = args.request.headers.get(signatureHeaderName);
info(ms.extractedPayload, { body, signatureHeader });
if (!signatureHeader) {
error(ms.noSignatureHeader);
return failureCallback(
{
code: 9901,
message: `No signature header found`,
},
{ body: jsonParse(body) ?? "Couldn't parse body" }
);
}
// 2. Make sure the webhook is coming from ninjavan
try {
const validSignature = verifyNinjaWebhookSignature({
signature: signatureHeader,
body,
secret: clientSecret,
});
if (!validSignature) {
error(ms.invalidSignature);
return failureCallback(
{
code: 9902,
message: `Invalid signature`,
},
{ body: jsonParse(body) ?? "Couldn't parse body" }
);
}
info(ms.validSignature);
} catch (err) {
error(ms.invalidSignature, { error: (err as Error).message });
return failureCallback(
{
code: 9902,
message: `Invalid signature: ${(err as Error).message}`,
},
{ body: jsonParse(body) ?? "Couldn't parse body" }
);
}
// 3. Extract the event
info(ms.extractingEvent);
const event = jsonParse(body) as NinjaWebhookEvent;
const eventType = event.status;
info(ms.extractedEvent, { event });
if (!eventType) {
error(ms.noEventType);
return failureCallback(
{
code: 9903,
message: `No event type found`,
},
{ body: jsonParse(body) ?? "Couldn't parse body" }
);
}
// 4. Handle the event
if (isNinjaWebhookEventType(eventType)) {
info(ms.validEventType, { eventType });
if (
args.registeredEvents.includes(eventType) ||
args.registeredEvents.includes("*")
) {
info(ms.registeredEventType, { eventType });
return successCallback({ event: eventType, ...event });
}
error(ms.notRegisteredEventType, { eventType });
return failureCallback(
{
code: 9904,
message: `Event type not registered: ${eventType}`,
},
{
event: eventType,
...event,
}
);
} else {
error(ms.invalidEventType, { eventType });
return failureCallback(
{
code: 9905,
message: `Invalid event type: ${eventType}`,
},
{ body: jsonParse(body) ?? "Couldn't parse body" }
);
}
},
/**
* @description - takes care of the whole process of creating order/s
* 1. Creates the order/s
* 2. Generates the waybill/s
*
* @recommended - provide your own `tracking_id`s, this function will
* make sure that ninjavan api used 'em to create orders
*
*
* @note - if you're using `requested_tracking_number` you need
* to know that when ninja cancels an order of yours, it reserves the
* tracking number used to create the order, so you won't be able
* to use it again. i.e you need to generate new ones every time you're
* using this function and keep those in sync with your system
*
* @param trackingNumbersPrefix - if you want to use `requested_tracking_number`
* you must provide your account prefix.
* @param logger - if true, this function will use its own logger
* instead of the wrapper's logger, so you can disable the wrapper's
* logger focus on this function's logs. @default false
* @param showSenderDetails - if true, this function will print sender
* details on the waybill, @default false
*/
async express(
args: Array<CreateOrderInput["input"] & { comments?: string }>,
trackingNumbersPrefix?: string,
showSenderDetails?: boolean,
_logger?: boolean
) {
// prepare logger
const loggerEnabled = _logger ?? logger ?? false;
const __logger = pinoLogger(loggerEnabled);
const _info = (log: string, child?: object) =>
__logger.child(child ?? {}).info(log);
const _error = (log: string, child?: object) =>
__logger.child(child ?? {}).error(log);
if (!showSenderDetails) showSenderDetails = false;
_info(ms.runExpress);
// prepare dependencies
const _token = (await getToken()) as string;
// map requested trackingNumber to trackingNumbers ninja generated
const map = new Map<string, string | undefined>();
const wantsTrackingNumber = args.some(
(arg, index) => !!arg.requested_tracking_number
);
if (wantsTrackingNumber) {
if (!trackingNumbersPrefix) {
throw new Error(ms.noTrackingNumbersPrefix);
}
args.forEach((arg, index) => {
if (arg.requested_tracking_number) {
map.set(arg.requested_tracking_number, " ");
}
});
}
_info(ms.wantTrackingNumber, { total: args.length, for: map.size });
// 1. Create the order/s
try {
const _ = await methods.createOrders(
args,
// strict mode, all or none get created
_token,
loggerEnabled,
true
);
// failed to create all orders
if (!_.ok) {
// failed to cancel all successfully created orders
if (!_.cancelation || !_.cancelation?.ok) {
throw new Error(`
💀 Ops! This is bad, we failed to cancel orders that we created!!
🔥 Failed to create orders: ${_.error?.join(", ")},
🔥 Failed to cancel orders: ${_.cancelation?.error?.join(", ")},
🔥 Try to cancel the orders that were just created 😅 one by one.
`);
}
throw new Error(_.error?.join(", "));
}
/**
*
* @description - cancels all orders that were created
* @returns
*/
const reverseCreation = async () => {
// prepare ids to cancel
const ids = _.data.map((order) => order.tracking_number);
// cancel all orders
return await methods.cancelOrders(ids, _token, loggerEnabled);
};
// make sure ninja used the provided trackingNumber/s
if (wantsTrackingNumber) {
for (const order of _.data) {
if (order.requested_tracking_number) {
const item = map.get(order.requested_tracking_number);
_info("view", {
map: [...map.entries()],
item,
});
if (!item) {
_error(ms.unexpectedTrackingNumber, {
requested:
trackingNumbersPrefix + order.requested_tracking_number,
used: order.tracking_number,
});
const { ok, error } = await reverseCreation();
throw new Error(
`This should never happen ${
!ok
? "unable to cancel some created orders" +
error?.join(", ")
: ""
}`
);