-
Notifications
You must be signed in to change notification settings - Fork 4
/
index.ts
1636 lines (1506 loc) · 41.2 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
export interface Dictionary<T> {
[index: string]: T;
}
const noop = (): void => {
// noop
};
const deprecated = {} as {
[key in 'expandFilter' | 'countInResource' | 'countInExpand']: () => void;
};
const addDeprecated = (
name: keyof typeof deprecated,
message: string,
): void => {
deprecated[name] = () => {
console.warn('pinejs-client deprecated:', message);
deprecated[name] = noop;
};
};
addDeprecated(
'expandFilter',
'`$filter: a: b: ...` is deprecated, please use `$filter: a: $any: { $alias: "x", $expr: x: b: ... }` instead.',
);
addDeprecated(
'countInResource',
"'`resource: 'a/$count'` is deprecated, please use `options: { $count: { ... } }` instead.",
);
addDeprecated(
'countInExpand',
"'`$expand: { 'a/$count': {...} }` is deprecated, please use `$expand: { a: { $count: {...} } }` instead.",
);
const mapObj = <T, R>(
obj: Dictionary<T>,
fn: (value: T, key: string) => R,
): R[] => Object.keys(obj).map((key) => fn(obj[key], key));
const NumberIsFinite: (v: any) => v is number =
(Number as any).isFinite || ((v) => typeof v === 'number' && isFinite(v));
const isString = (v: any): v is string => typeof v === 'string';
const isBoolean = (v: any): v is boolean => v === true || v === false;
const isDate = (v: any): v is Date =>
Object.prototype.toString.call(v) === '[object Date]';
const isObject = (v: any): v is AnyObject =>
typeof v != null && typeof v === 'object';
const isValidOption = (
key: string,
): key is keyof ODataOptionsWithoutCount & string => {
return (
key === '$select' ||
key === '$filter' ||
key === '$expand' ||
key === '$orderby' ||
key === '$top' ||
key === '$skip' ||
key === '$format'
);
};
const encodedSlash = encodeURIComponent('/');
const encodedCount = encodeURIComponent('$count');
const trailingCountRegex = new RegExp(
`(?:(?:${encodedSlash})|/)${encodedCount}$`,
);
interface PollOnObj {
unsubscribe: () => void;
}
class Poll<T extends PromiseResultTypes> {
private subscribers: {
error: Array<(response: T) => void>;
data: Array<(err: any) => void>;
} = {
error: [],
data: [],
};
private stopped = false;
private pollInterval?: ReturnType<typeof setTimeout>;
private requestFn: null | (() => Promise<T>);
constructor(requestFn: () => Promise<T>, private intervalTime = 10000) {
this.requestFn = requestFn;
this.start();
}
public setPollInterval(intervalTime: number): void {
this.intervalTime = intervalTime;
this.restartTimeout();
}
public async runRequest(): Promise<void> {
if (this.stopped || this.requestFn == null) {
return;
}
try {
const response = await this.requestFn();
if (this.stopped) {
return;
}
this.restartTimeout();
// Catch errors in event subscribers so that they don't trigger
// the 'catch' below, and that subsequent subscribers will still
// be called
this.subscribers.data.forEach((fn) => {
try {
fn(response);
} catch (error) {
console.error(
'pinejs-client error: Caught error in data event subscription:',
error,
);
}
});
} catch (err: any) {
if (this.stopped) {
return;
}
this.restartTimeout();
this.subscribers.error.forEach((fn) => {
try {
fn(err);
} catch (error) {
console.error(
'pinejs-client error: Caught error in error event subscription:',
error,
);
}
});
}
}
public on(name: 'data', fn: (response: Promise<T>) => void): PollOnObj;
public on(name: 'error', fn: (err: any) => void): PollOnObj;
public on(
name: keyof Poll<T>['subscribers'],
fn: (value: any) => void,
): PollOnObj {
const subscribers = this.subscribers[name] as Array<(value: any) => void>;
const index = subscribers.push(fn) - 1;
return {
unsubscribe: () => delete this.subscribers[name][index],
};
}
public start(): void {
this.stopped = false;
this.runRequest();
}
public stop(): void {
if (this.pollInterval) {
clearTimeout(this.pollInterval);
}
this.stopped = true;
}
public destroy(): void {
this.stop();
this.requestFn = null;
this.subscribers.error.length = 0;
this.subscribers.data.length = 0;
}
private restartTimeout(): void {
if (this.stopped) {
return;
}
if (this.pollInterval) {
clearTimeout(this.pollInterval);
}
this.pollInterval = setTimeout(() => this.runRequest(), this.intervalTime);
}
}
const isPrimitive = (value?: unknown): value is Primitive => {
return (
value === null ||
isString(value) ||
NumberIsFinite(value) ||
isBoolean(value) ||
isDate(value)
);
};
// Escape a resource name (string), or resource path (array)
const escapeResource = (resource: string | string[]): string => {
if (isString(resource)) {
resource = encodeURIComponent(resource);
} else if (Array.isArray(resource)) {
resource = resource.map(encodeURIComponent).join('/');
} else {
throw new Error('Not a valid resource: ' + typeof resource);
}
return resource.replace(trailingCountRegex, '/$count');
};
// Escape a primitive value
const escapeValue = (value: Primitive): string | number | boolean | null => {
if (isString(value)) {
value = value.replace(/'/g, "''");
return `'${encodeURIComponent(value)}'`;
} else if (isDate(value)) {
return `datetime'${value.toISOString()}'`;
} else if (value === null || NumberIsFinite(value) || isBoolean(value)) {
return value;
} else {
throw new Error('Not a valid value: ' + typeof value);
}
};
const escapeParameterAlias = (value: unknown): string => {
if (!isString(value)) {
throw new Error(
`Parameter alias reference must be a string, got: ${typeof value}`,
);
}
return `@${encodeURIComponent(value)}`;
};
const join = (strOrArray: string | string[], separator = ','): string => {
if (isString(strOrArray)) {
return strOrArray;
} else if (Array.isArray(strOrArray)) {
return strOrArray.join(separator);
} else {
throw new Error('Expected a string or array, got: ' + typeof strOrArray);
}
};
// Join together a bunch of statements making sure the whole lot is correctly parenthesised
const bracketJoin = (arr: string[][], separator: string): string[] => {
if (arr.length === 1) {
return arr[0];
}
const resultArr: string[] = [];
arr
.map((subArr) => {
if (subArr.length > 1) {
return `(${subArr.join('')})`;
}
return subArr[0];
})
.forEach((str, i) => {
if (i !== 0) {
resultArr.push(separator);
}
resultArr.push(str);
});
return resultArr;
};
// Add the parentKey + operator if it exists.
const addParentKey = (
filter: string[] | string | boolean | number | null,
parentKey?: string[],
operator = ' eq ',
): string[] => {
if (parentKey != null) {
if (Array.isArray(filter)) {
if (filter.length === 1) {
filter = filter[0];
} else {
filter = `(${filter.join('')})`;
}
} else {
filter = `${filter}`;
}
return [escapeResource(parentKey), operator, filter];
}
if (Array.isArray(filter)) {
return filter;
}
return [`${filter}`];
};
const applyBinds = (
filter: string,
params: Dictionary<Filter>,
parentKey?: string[],
): string[] => {
for (const index of Object.keys(params)) {
const param = params[index];
let paramStr = `(${buildFilter(param).join('')})`;
// Escape $ for filter.replace
paramStr = paramStr.replace(/\$/g, '$$$$');
filter = filter.replace(
new RegExp(`\\$${index}([^a-zA-Z0-9]|$)`, 'g'),
`${paramStr}$1`,
);
}
filter = `(${filter})`;
return addParentKey(filter, parentKey);
};
const filterOperation = (
filter: FilterOperationValue,
operator: FilterOperationKey,
parentKey?: string[],
): string[] => {
const op = ' ' + operator.slice(1) + ' ';
if (isPrimitive(filter)) {
const filterStr = escapeValue(filter);
return addParentKey(filterStr, parentKey, op);
} else if (Array.isArray(filter)) {
const filterArr = handleFilterArray(filter);
const filterStr = bracketJoin(filterArr, op);
return addParentKey(filterStr, parentKey);
} else if (isObject(filter)) {
const result = handleFilterObject(filter);
if (result.length < 1) {
throw new Error(
`${operator} objects must have at least 1 property, got: ${JSON.stringify(
filter,
)}`,
);
}
if (result.length === 1) {
return addParentKey(result[0], parentKey, op);
} else {
const filterStr = bracketJoin(result, op);
return addParentKey(filterStr, parentKey);
}
} else {
throw new Error(
'Expected null/string/number/bool/obj/array, got: ' + typeof filter,
);
}
};
const filterFunction = (
filter: FilterFunctionValue,
fnIdentifier: FilterFunctionKey,
parentKey?: string[],
): string[] => {
const fnName = fnIdentifier.slice(1);
if (isPrimitive(filter)) {
const operands = [];
if (parentKey != null) {
operands.push(escapeResource(parentKey));
}
operands.push(escapeValue(filter));
return [`${fnName}(${operands.join()})`];
} else if (Array.isArray(filter)) {
const filterArr = handleFilterArray(filter);
let filterStr = filterArr.map((subArr) => subArr.join('')).join(',');
filterStr = `${fnName}(${filterStr})`;
return addParentKey(filterStr, parentKey);
} else if (isObject(filter)) {
const filterArr = handleFilterObject(filter);
let filterStr = filterArr.map((subArr) => subArr.join('')).join(',');
filterStr = `${fnName}(${filterStr})`;
return addParentKey(filterStr, parentKey);
} else {
throw new Error(
`Expected null/string/number/obj/array, got: ${typeof filter}`,
);
}
};
type FilterType<Operator extends keyof FilterObj> = NonNullable<
FilterObj[Operator]
>;
// Handle special cases for all the different $ operators.
const handleFilterOperator = (
filter: FilterObj[string],
operator: keyof FilterObj,
parentKey?: string[],
): string[] => {
switch (operator) {
case '$ne':
case '$eq':
case '$gt':
case '$ge':
case '$lt':
case '$le':
case '$add':
case '$sub':
case '$mul':
case '$div':
case '$mod':
return filterOperation(
filter as FilterType<typeof operator>,
operator,
parentKey,
);
// break
case '$contains':
case '$endswith':
case '$startswith':
case '$length':
case '$indexof':
case '$substring':
case '$tolower':
case '$toupper':
case '$trim':
case '$concat':
case '$year':
case '$month':
case '$day':
case '$hour':
case '$minute':
case '$second':
case '$fractionalseconds':
case '$date':
case '$time':
case '$totaloffsetminutes':
case '$now':
case '$maxdatetime':
case '$mindatetime':
case '$totalseconds':
case '$round':
case '$floor':
case '$ceiling':
case '$isof':
case '$cast':
return filterFunction(
filter as FilterType<typeof operator>,
operator,
parentKey,
);
// break
case '$raw': {
filter = filter as FilterType<typeof operator>;
if (isString(filter)) {
filter = `(${filter})`;
return addParentKey(filter, parentKey);
} else if (!isPrimitive(filter)) {
if (Array.isArray(filter)) {
const [rawFilter, ...params] = filter;
if (!isString(rawFilter)) {
throw new Error(
`First element of array for ${operator} must be a string, got: ${typeof rawFilter}`,
);
}
const mappedParams: Dictionary<Filter> = {};
for (let index = 0; index < params.length; index++) {
mappedParams[index + 1] = params[index];
}
return applyBinds(rawFilter, mappedParams, parentKey);
} else if (isObject(filter)) {
const filterStr = filter.$string;
if (!isString(filterStr)) {
throw new Error(
`$string element of object for ${operator} must be a string, got: ${typeof filterStr}`,
);
}
const mappedParams: Dictionary<Filter> = {};
for (const index in filter) {
if (index !== '$string') {
if (!/^[a-zA-Z0-9]+$/.test(index)) {
throw new Error(
`${operator} param names must contain only [a-zA-Z0-9], got: ${index}`,
);
}
mappedParams[index] = filter[index] as Filter;
}
}
return applyBinds(filterStr, mappedParams, parentKey);
}
}
throw new Error(
`Expected string/array/object for ${operator}, got: ${typeof filter}`,
);
}
// break
case '$': {
const resource = escapeResource(filter as FilterType<typeof operator>);
return addParentKey(resource, parentKey);
}
case '$count': {
let keys = ['$count'];
if (parentKey != null) {
keys = parentKey.concat(keys);
}
return buildFilter(filter as Filter, keys);
}
// break
case '$and':
case '$or': {
const filterStr = buildFilter(
filter as FilterType<typeof operator>,
undefined,
` ${operator.slice(1)} `,
);
return addParentKey(filterStr, parentKey);
}
// break
case '$in': {
filter = filter as FilterType<typeof operator>;
if (isPrimitive(filter)) {
const filterStr = escapeValue(filter);
return addParentKey(filterStr, parentKey, ' eq ');
} else if (Array.isArray(filter)) {
if (filter.every(isPrimitive)) {
const filterStr = handleFilterArray(filter, undefined, 1);
const inStr = bracketJoin(filterStr, ', ').join('');
return addParentKey(`(${inStr})`, parentKey, ' in ');
} else {
const filterStr = handleFilterArray(filter, parentKey, 1);
return bracketJoin(filterStr, ' or ');
}
} else if (isObject(filter)) {
const filterArr = handleFilterObject(filter, parentKey);
if (filterArr.length < 1) {
throw new Error(
`${operator} objects must have at least 1 property, got: ${JSON.stringify(
filter,
)}`,
);
}
return bracketJoin(filterArr, ' or ');
} else {
throw new Error(
`Expected null/string/number/bool/obj/array, got: ${typeof filter}`,
);
}
}
// break
case '$not': {
const filterStr = `not(${buildFilter(
filter as FilterType<typeof operator>,
).join('')})`;
return addParentKey(filterStr, parentKey);
}
// break
case '$any':
case '$all': {
filter = filter as FilterType<typeof operator>;
const alias = filter.$alias;
const expr = filter.$expr;
if (alias == null) {
throw new Error(
`Lambda expression (${operator}) has no alias defined.`,
);
}
if (expr == null) {
throw new Error(`Lambda expression (${operator}) has no expr defined.`);
}
// Disable the expandFilter deprecation notice when inside a lambda expr
const deprecatedFn = (deprecated.expandFilter = noop);
let filterStr;
try {
filterStr = buildFilter(expr).join('');
} finally {
deprecated.expandFilter = deprecatedFn;
}
filterStr = `${operator.slice(1)}(${alias}:${filterStr})`;
return addParentKey(filterStr, parentKey, '/');
}
// break
default:
throw new Error(`Unrecognised operator: '${operator}'`);
}
};
const handleFilterObject = (
filter: FilterObj,
parentKey?: string[],
): string[][] => {
return mapObj(filter, (value, key) => {
if (value === undefined) {
throw new Error(
`'${key}' was present on a filter object but undefined, did you mean to use null instead?`,
);
}
if (key[0] === '$') {
return handleFilterOperator(value, key, parentKey);
} else if (key[0] === '@') {
const parameterAlias = escapeParameterAlias(value);
return addParentKey(parameterAlias, parentKey);
} else {
let keys = [key];
if (parentKey != null) {
if (parentKey.length > 0) {
deprecated.expandFilter();
}
keys = parentKey.concat(keys);
}
return buildFilter(value as Filter, keys);
}
});
};
const handleFilterArray = (
filter: FilterArray,
parentKey?: string[],
minElements = 2,
): string[][] => {
if (filter.length < minElements) {
throw new Error(
`Filter arrays must have at least ${minElements} elements, got: ${JSON.stringify(
filter,
)}`,
);
}
return filter.map((value) => {
return buildFilter(value, parentKey);
});
};
// Turn a filter query object into an OData $filter string
const buildFilter = (
filter: Filter,
parentKey?: string[],
joinStr?: string,
): string[] => {
if (isPrimitive(filter)) {
const filterStr = escapeValue(filter);
return addParentKey(filterStr, parentKey);
} else if (Array.isArray(filter)) {
const filterArr = handleFilterArray(filter);
const filterStr = bracketJoin(filterArr, joinStr ?? ' or ');
return addParentKey(filterStr, parentKey);
} else if (isObject(filter)) {
const filterArr = handleFilterObject(filter, parentKey);
return bracketJoin(filterArr, joinStr ?? ' and ');
} else {
throw new Error(
`Expected null/string/number/obj/array, got: ${typeof filter}`,
);
}
};
const buildOrderBy = (orderby: OrderBy): string => {
if (isString(orderby)) {
return orderby;
} else if (Array.isArray(orderby)) {
if (orderby.length === 0) {
throw new Error(`'$orderby' arrays have to have at least 1 element`);
}
const result = orderby.map((value) => {
if (Array.isArray(value)) {
throw new Error(`'$orderby' cannot have nested arrays`);
}
return buildOrderBy(value);
});
return join(result);
} else if (isObject(orderby)) {
const result = mapObj(orderby, (dir, key) => {
if (dir !== 'asc' && dir !== 'desc') {
throw new Error(`'$orderby' direction must be 'asc' or 'desc'`);
}
return `${key} ${dir}`;
});
if (result.length !== 1) {
throw new Error(
`'$orderby' objects must have exactly one element, got ${result.length} elements`,
);
}
return result[0];
} else {
throw new Error(
`'$orderby' option has to be either a string, array, or object`,
);
}
};
const buildOption = (
option: string,
value: ODataOptionsWithoutCount[string],
): string => {
let compiledValue: string = '';
switch (option) {
case '$filter':
compiledValue = buildFilter(value as Filter).join('');
break;
case '$expand':
compiledValue = buildExpand(value as Expand);
break;
case '$orderby':
compiledValue = buildOrderBy(value as OrderBy);
break;
case '$top':
case '$skip':
const num = value;
if (!NumberIsFinite(num)) {
throw new Error(`'${option}' option has to be a number`);
}
compiledValue = '' + num;
break;
case '$select':
const select = value;
if (isString(select)) {
compiledValue = join(select);
} else if (Array.isArray(select)) {
if (select.length === 0) {
throw new Error(`'${option}' arrays have to have at least 1 element`);
}
compiledValue = join(select as string[]);
} else {
throw new Error(
`'${option}' option has to be either a string or array`,
);
}
break;
default:
// Escape parameter aliases as primitives
if (option[0] === '@') {
if (!isPrimitive(value)) {
throw new Error(
`Unknown type for parameter alias option '${option}': ${typeof value}`,
);
}
compiledValue = '' + escapeValue(value);
}
// Unknown values are left as-is
else if (Array.isArray(value)) {
compiledValue = join(value as string[]);
} else if (isString(value)) {
compiledValue = value;
} else if (isBoolean(value) || NumberIsFinite(value)) {
compiledValue = value.toString();
} else {
throw new Error(`Unknown type for option ${typeof value}`);
}
}
return `${option}=${compiledValue}`;
};
const handleExpandOptions = (
expand: ODataOptions,
parentKey: string,
): string => {
if (parentKey.endsWith('/$count')) {
deprecated.countInExpand();
}
if (expand.hasOwnProperty('$count')) {
const keys = Object.keys(expand);
if (keys.length > 1) {
throw new Error(
`When using '$expand: a: $count: ...' you can only specify $count, got: '${JSON.stringify(
keys,
)}'`,
);
}
expand = expand.$count!;
parentKey += '/$count';
}
const expandOptions = mapObj(expand, (value, key) => {
if (key[0] === '$') {
if (!isValidOption(key)) {
throw new Error(`Unknown key option '${key}'`);
}
return buildOption(key, value);
} else {
throw new Error(
`'$expand: ${parentKey}: ${key}: ...' is invalid, use '$expand: ${parentKey}: $expand: ${key}: ...' instead.`,
);
}
});
let expandStr = expandOptions.join(';');
if (expandStr.length > 0) {
expandStr = `(${expandStr})`;
}
expandStr = escapeResource(parentKey) + expandStr;
return expandStr;
};
const handleExpandObject = (expand: ResourceExpand): string[] => {
const expands = mapObj(expand, (value, key) => {
if (key[0] === '$') {
throw new Error(
'Cannot have expand options without first expanding something!',
);
}
if (isPrimitive(value)) {
const jsonValue = JSON.stringify(value);
throw new Error(
`'$expand: ${key}: ${jsonValue}' is invalid, use '$expand: ${key}: $expand: ${jsonValue}' instead.`,
);
}
if (Array.isArray(value)) {
throw new Error(
`'$expand: ${key}: [...]' is invalid, use '$expand: ${key}: {...}' instead.`,
);
}
return handleExpandOptions(value, key);
});
return expands;
};
const handleExpandArray = (
expands: Array<string | ResourceExpand>,
): string[] => {
if (expands.length < 1) {
throw new Error(
`Expand arrays must have at least 1 elements, got: ${JSON.stringify(
expands,
)}`,
);
}
return expands.map((expand) => {
return buildExpand(expand);
});
};
const buildExpand = (expand: Expand): string => {
if (isPrimitive(expand)) {
return escapeResource(expand);
} else if (Array.isArray(expand)) {
const expandStr = handleExpandArray(expand);
return join(expandStr);
} else if (isObject(expand)) {
const expandStr = handleExpandObject(expand);
return join(expandStr);
} else {
throw new Error(`Unknown type for expand '${typeof expand}'`);
}
};
const validParams = [
'apiPrefix',
'passthrough',
'passthroughByMethod',
'retry',
] as const;
export type PreparedFn<T extends Dictionary<ParameterAlias>, U> = (
parameterAliases?: T,
body?: Params['body'],
passthrough?: Params['passthrough'],
) => U;
export type RetryParametersObj = {
canRetry?: (err: any) => boolean;
onRetry?: (
prevErr: any,
delayMs: number,
attempt: number,
maxAttempts: number,
) => void;
minDelayMs?: number;
maxDelayMs?: number;
maxAttempts?: number;
};
export type RetryParameters = RetryParametersObj | false;
export abstract class PinejsClientCore<PinejsClient> {
public apiPrefix: string = '/';
public passthrough: AnyObject = {};
public passthroughByMethod: AnyObject = {};
public backendParams?: AnyObject;
public retry: RetryParameters = false;
// `backendParams` must be used by a backend for any additional parameters it may have.
constructor(params: string | Params) {
if (isString(params)) {
params = { apiPrefix: params };
}
if (isObject(params)) {
for (const validParam of validParams) {
const value = params[validParam];
if (value != null) {
(this[
validParam
] as PinejsClientCore<PinejsClient>[typeof validParam]) = value;
}
}
}
}
private canRetryDefaultHandler(err: any) {
const code = err?.statusCode;
return code == null || code === 429 || (code >= 500 && code < 600);
}
protected async callWithRetry<T>(
fnCall: () => Promise<T>,
retry?: RetryParameters,
): Promise<T> {
// Explicitly passing retry as false disables retrying for this call.
if (retry === false || (retry == null && this.retry === false)) {
return await fnCall();
}
const retryDefaultParameters = this.retry || {};
const retryParameters = retry || {};
const minDelayMs =
retryParameters.minDelayMs ?? retryDefaultParameters.minDelayMs;
const maxDelayMs =
retryParameters.maxDelayMs ?? retryDefaultParameters.maxDelayMs;
const maxAttempts =
retryParameters.maxAttempts ?? retryDefaultParameters.maxAttempts;
if (minDelayMs == null || minDelayMs <= 0) {
throw new Error(
`pinejs-client minDelayMs must be a positive integer, got: '${minDelayMs}'`,
);
}
if (maxDelayMs == null || maxDelayMs <= 0) {
throw new Error(
`pinejs-client maxDelayMs must be a positive integer, got: '${maxDelayMs}'`,
);
}
if (maxAttempts == null || maxAttempts <= 0) {
throw new Error(
`pinejs-client maxAttempts be a positive integer, got: '${maxDelayMs}'`,
);
}
if (minDelayMs > maxDelayMs) {
throw new Error(
'pinejs-client maxDelayMs must be greater than or equal to minDelayMs',
);
}
const onRetryHandler =
retryParameters.onRetry ?? retryDefaultParameters.onRetry;
let attempt = 1;
const canRetryHandler =
retryParameters.canRetry ??
retryDefaultParameters.canRetry ??
this.canRetryDefaultHandler;
while (true) {
try {
return await fnCall();
} catch (err) {
if (attempt >= maxAttempts || !canRetryHandler(err)) {
throw err;
}
const delayMs = Math.min(2 ** (attempt - 1) * minDelayMs, maxDelayMs);
// note that attempt is incremented before calling onRetryHandler because
// retries effectively begin with attempt number 2.
attempt++;
onRetryHandler?.(err, delayMs, attempt, maxAttempts);
await new Promise<void>((resolve) => {
setTimeout(resolve, delayMs);
});
}
}
}
// `backendParams` must be used by a backend for any additional parameters it may have.
public clone(
params: string | Params,
backendParams?: AnyObject,
): PinejsClient {
if (isString(params)) {
params = { apiPrefix: params };
}
const cloneParams: typeof params = {};
for (const validParam of validParams) {
if (this[validParam] != null) {
(cloneParams[
validParam
] as PinejsClientCore<PinejsClient>[typeof validParam]) =
this[validParam];
}
const paramValue = params?.[validParam];
if (paramValue != null) {
(cloneParams[
validParam
] as PinejsClientCore<PinejsClient>[typeof validParam]) = paramValue;
}
}
let cloneBackendParams: typeof backendParams = {};
if (isObject(this.backendParams)) {
cloneBackendParams = { ...this.backendParams };
}
if (isObject(backendParams)) {
cloneBackendParams = { ...cloneBackendParams, ...backendParams };
}
return new (this.constructor as new (
params: Params,
backendParams: AnyObject,
) => PinejsClient)(cloneParams, cloneBackendParams);
}
public async get(
params: Params & {
options: { $count: NonNullable<ODataOptions['$count']> };
},
): Promise<number>;
public async get(
params: Params & { id: NonNullable<Params['id']> },
): Promise<AnyObject | undefined>;
public async get(params: Omit<Params, 'id'>): Promise<AnyObject[]>;
public async get(params: Params): Promise<PromiseResultTypes> {
if (isString(params)) {
throw new Error(
'`get(url)` is no longer supported, please use `get({ url })` instead.',