-
Notifications
You must be signed in to change notification settings - Fork 122
/
Copy pathrestLink.ts
executable file
·1414 lines (1276 loc) · 43.4 KB
/
restLink.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 {
OperationTypeNode,
OperationDefinitionNode,
FragmentDefinitionNode,
// Query Nodes
DirectiveNode,
DocumentNode,
FieldNode,
SelectionSetNode,
} from 'graphql';
import {
ApolloLink,
Observable,
Operation,
NextLink,
FetchResult,
} from '@apollo/client/core';
import {
hasDirectives,
getMainDefinition,
getFragmentDefinitions,
createFragmentMap,
addTypenameToDocument,
FragmentMap,
isField,
isInlineFragment,
resultKeyNameFromField,
checkDocument,
removeDirectivesFromDocument,
} from '@apollo/client/utilities';
import { graphql } from './utils/graphql';
import * as qs from 'qs';
export type DirectiveInfo = {
[fieldName: string]: { [argName: string]: any };
};
export type ExecInfo = {
isLeaf: boolean;
resultKey: string;
directives: DirectiveInfo;
field: FieldNode;
};
export type Resolver = (
fieldName: string,
rootValue: any,
args: any,
context: any,
info: ExecInfo,
) => any;
export namespace RestLink {
export type URI = string;
export type Endpoint = string;
export interface EndpointOptions {
uri: Endpoint;
responseTransformer?: ResponseTransformer | null;
}
export interface Endpoints {
[endpointKey: string]: Endpoint | EndpointOptions;
}
export type Header = string;
export interface HeadersHash {
[headerKey: string]: Header;
}
export type InitializationHeaders = HeadersHash | Headers | string[][];
export type HeadersMergePolicy = (...headerGroups: Headers[]) => Headers;
export interface FieldNameNormalizer {
(fieldName: string, keypath?: string[]): string;
}
export interface TypePatcherContext {
resolverParams: {
fieldName: string;
root: any;
args: any;
context: RequestContext;
info: ExecInfo;
};
}
/** injects __typename using user-supplied code */
export interface FunctionalTypePatcher {
(
data: any,
outerType: string,
patchDeeper: FunctionalTypePatcher,
context: TypePatcherContext,
): any;
}
/** Table of mappers that help inject __typename per type described therein */
export interface TypePatcherTable {
[typename: string]: FunctionalTypePatcher;
}
export interface SerializedBody {
body: any;
headers: InitializationHeaders;
}
export interface Serializer {
(data: any, headers: Headers): SerializedBody;
}
export interface Serializers {
[bodySerializer: string]: Serializer;
}
export type CustomFetch = (
request: RequestInfo,
init: RequestInit,
) => Promise<Response>;
export type ResponseTransformer = (data: any, typeName: string) => any;
export interface RestLinkHelperProps {
/** Arguments passed in via normal graphql parameters */
args: { [key: string]: any };
/** Arguments added via @export(as: ) directives */
exportVariables: { [key: string]: any };
/** Arguments passed directly to @rest(params: ) */
// params: { [key: string]: any };
/** Apollo Context */
context: { [key: string]: any };
/** All arguments passed to the `@rest(...)` directive */
'@rest': { [key: string]: any };
}
export interface PathBuilderProps extends RestLinkHelperProps {
replacer: (opts: RestLinkHelperProps) => string;
}
/**
* Used for any Error from the server when requests:
* - terminate with HTTP Status >= 300
* - and the response contains no data or errors
*/
export type ServerError = Error & {
response: Response;
result: any;
statusCode: number;
};
export type Options = {
/**
* The URI to use when fetching operations.
*
* Optional if endpoints provides a default.
*/
uri?: URI;
/**
* A root endpoint (uri) to apply paths to or a map of endpoints.
*/
endpoints?: Endpoints;
/**
* An object representing values to be sent as headers on the request.
*/
headers?: InitializationHeaders;
/**
* A function that takes the response field name and converts it into a GraphQL compliant name
*
* @note This is called *before* @see typePatcher so that it happens after
* optional-field-null-insertion.
*/
fieldNameNormalizer?: FieldNameNormalizer;
/**
* A function that takes a GraphQL-compliant field name and converts it back into an endpoint-specific name
* Can be overridden at the mutation-call-site (in the rest-directive).
*/
fieldNameDenormalizer?: FieldNameNormalizer;
/**
* Structure to allow you to specify the __typename when you have nested objects in your REST response!
*
* If you want to force Required Properties, you can throw an error in your patcher,
* or `delete` a field from the data response provided to your typePatcher function!
*
* @note: This is called *after* @see fieldNameNormalizer because that happens
* after optional-nulls insertion, and those would clobber normalized names.
*
* @warning: We're not thrilled with this API, and would love a better alternative before we get to 1.0.0
* Please see proposals considered in https://github.com/apollographql/apollo-link-rest/issues/48
* And consider submitting alternate solutions to the problem!
*/
typePatcher?: TypePatcherTable;
/**
* The credentials policy you want to use for the fetch call.
*/
credentials?: 'omit' | 'same-origin' | 'include';
/**
* Use a custom fetch to handle REST calls.
*/
customFetch?: CustomFetch;
/**
* Add serializers that will serialize the body before it is emitted and will pass on
* headers to update the request.
*/
bodySerializers?: Serializers;
/**
* Set the default serializer for the link
* @default JSON serialization
*/
defaultSerializer?: Serializer;
/**
* Parse the response body of an HTTP request into the format that Apollo expects.
*/
responseTransformer?: ResponseTransformer;
};
/** @rest(...) Directive Options */
export interface DirectiveOptions {
/**
* What HTTP method to use.
* @default `GET`
*/
method?: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
/** What GraphQL type to name the response */
type?: string;
/**
* What path (including query) to use
* - @optional if you provide @see DirectiveOptions.pathBuilder
*/
path?: string;
/**
* What endpoint to select from the map of endpoints available to this link.
* @default `RestLink.endpoints[DEFAULT_ENDPOINT_KEY]`
*/
endpoint?: string;
/**
* Function that constructs a request path out of the Environmental
* state when processing this @rest(...) call.
*
* - @optional if you provide: @see DirectiveOptions.path
* - **note**: providing this function means it's your responsibility to call
* encodeURIComponent directly if needed!
*
* Warning: This is an Advanced API and we are looking for syntactic & ergonomics feedback.
*/
pathBuilder?: (props: PathBuilderProps) => string;
/**
* Optional method that constructs a RequestBody out of the Environmental state
* when processing this @rest(...) call.
* @default function that extracts the bodyKey from the args.
*
* Warning: This is an Advanced API and we are looking for syntactic & ergonomics feedback.
*/
bodyBuilder?: (props: RestLinkHelperProps) => object;
/**
* Optional field that defines the name of the env var to extract and use as the body
* @default "input"
* @see https://dev-blog.apollodata.com/designing-graphql-mutations-e09de826ed97
*/
bodyKey?: string;
/**
* Optional serialization function or a key that will be used look up the serializer to serialize the request body before transport.
* @default if null will fallback to the default serializer
*/
bodySerializer?: RestLink.Serializer | string;
/**
* A per-request name denormalizer, this permits special endpoints to have their
* field names remapped differently from the default.
* @default Uses RestLink.fieldNameDenormalizer
*/
fieldNameDenormalizer?: RestLink.FieldNameNormalizer;
/**
* A per-request name normalizer, this permits special endpoints to have their
* field names remapped differently from the default.
* @default Uses RestLink.fieldNameDenormalizer
*/
fieldNameNormalizer?: RestLink.FieldNameNormalizer;
/**
* A method to allow insertion of __typename deep in response objects
*/
typePatcher?: RestLink.FunctionalTypePatcher;
}
}
const popOneSetOfArrayBracketsFromTypeName = (typename: string): string => {
const noSpace = typename.replace(/\s/g, '');
const sansOneBracketPair = noSpace.replace(
/\[(.*)\]/,
(str, matchStr, offset, fullStr) => {
return (
((matchStr != null && matchStr.length) > 0 ? matchStr : null) || noSpace
);
},
);
return sansOneBracketPair;
};
const addTypeNameToResult = (
result: any[] | object,
__typename: string,
typePatcher: RestLink.FunctionalTypePatcher,
typePatcherContext: RestLink.TypePatcherContext,
): any[] | object => {
if (Array.isArray(result)) {
const fixedTypename = popOneSetOfArrayBracketsFromTypeName(__typename);
// Recursion needed for multi-dimensional arrays
return result.map(e =>
addTypeNameToResult(e, fixedTypename, typePatcher, typePatcherContext),
);
}
if (
null == result ||
typeof result === 'number' ||
typeof result === 'boolean' ||
typeof result === 'string'
) {
return result;
}
return typePatcher(result, __typename, typePatcher, typePatcherContext);
};
const quickFindRestDirective = (field: FieldNode): DirectiveNode | null => {
if (field.directives && field.directives.length) {
return field.directives.find(directive => 'rest' === directive.name.value);
}
return null;
};
/**
* The way graphql works today, it doesn't hand us the AST tree for our query, it hands us the ROOT
* This method searches for REST-directive-attached nodes that are named to match this query.
*
* A little bit of wasted compute, but alternative would be a patch in graphql-anywhere.
*
* @param resultKey SearchKey for REST directive-attached item matching this sub-query
* @param current current node in the REST-JSON-response
* @param mainDefinition Parsed Query Definition
* @param fragmentMap Map of Named Fragments
* @param currentSelectionSet Current selection set we're filtering by
*/
function findRestDirectivesThenInsertNullsForOmittedFields(
resultKey: string,
current: any[] | object, // currentSelectionSet starts at root, so wait until we're inside a Field tagged with an @rest directive to activate!
mainDefinition: OperationDefinitionNode | FragmentDefinitionNode,
fragmentMap: FragmentMap,
currentSelectionSet: SelectionSetNode,
): any[] | object {
if (
currentSelectionSet == null ||
null == current ||
typeof current === 'number' ||
typeof current === 'boolean' ||
typeof current === 'string'
) {
return current;
}
currentSelectionSet.selections.forEach(node => {
if (isInlineFragment(node)) {
findRestDirectivesThenInsertNullsForOmittedFields(
resultKey,
current,
mainDefinition,
fragmentMap,
node.selectionSet,
);
} else if (node.kind === 'FragmentSpread') {
const fragment = fragmentMap[node.name.value];
findRestDirectivesThenInsertNullsForOmittedFields(
resultKey,
current,
mainDefinition,
fragmentMap,
fragment.selectionSet,
);
} else if (isField(node)) {
const name = resultKeyNameFromField(node);
if (name === resultKey && quickFindRestDirective(node) != null) {
// Jackpot! We found our selectionSet!
insertNullsForAnyOmittedFields(
current,
mainDefinition,
fragmentMap,
node.selectionSet,
);
} else {
findRestDirectivesThenInsertNullsForOmittedFields(
resultKey,
current,
mainDefinition,
fragmentMap,
node.selectionSet,
);
}
} else {
// This will give a TypeScript build-time error if you did something wrong or the AST changes!
return ((node: never): never => {
throw new Error('Unhandled Node Type in SelectionSetNode.selections');
})(node);
}
});
// Return current to have our result pass to next link in async promise chain!
return current;
}
/**
* Recursively walks a handed object in parallel with the Query SelectionSet,
* and inserts `null` for any field that is missing from the response.
*
* This is needed because ApolloClient will throw an error automatically if it's
* missing -- effectively making all of rest-link's selections implicitly non-optional.
*
* If you want to implement required fields, you need to use typePatcher to *delete*
* fields when they're null and you want the query to fail instead.
*
* @param current Current object we're patching
* @param mainDefinition Parsed Query Definition
* @param fragmentMap Map of Named Fragments
* @param currentSelectionSet Current selection set we're filtering by
*/
function insertNullsForAnyOmittedFields(
current: any[] | object, // currentSelectionSet starts at root, so wait until we're inside a Field tagged with an @rest directive to activate!
mainDefinition: OperationDefinitionNode | FragmentDefinitionNode,
fragmentMap: FragmentMap,
currentSelectionSet: SelectionSetNode,
): void {
if (
null == current ||
typeof current === 'number' ||
typeof current === 'boolean' ||
typeof current === 'string'
) {
return;
}
if (Array.isArray(current)) {
// If our current value is an array, process our selection set for each entry.
current.forEach(c =>
insertNullsForAnyOmittedFields(
c,
mainDefinition,
fragmentMap,
currentSelectionSet,
),
);
return;
}
currentSelectionSet.selections.forEach(node => {
if (isInlineFragment(node)) {
insertNullsForAnyOmittedFields(
current,
mainDefinition,
fragmentMap,
node.selectionSet,
);
} else if (node.kind === 'FragmentSpread') {
const fragment = fragmentMap[node.name.value];
insertNullsForAnyOmittedFields(
current,
mainDefinition,
fragmentMap,
fragment.selectionSet,
);
} else if (isField(node)) {
const value = current[node.name.value];
if (node.name.value === '__typename') {
// Don't mess with special fields like __typename
} else if (typeof value === 'undefined') {
// Patch in a null where the field would have been marked as missing
current[node.name.value] = null;
} else if (
value != null &&
typeof value === 'object' &&
node.selectionSet != null
) {
insertNullsForAnyOmittedFields(
value,
mainDefinition,
fragmentMap,
node.selectionSet,
);
} else {
// Other types (string, number) do not need recursive patching!
}
} else {
// This will give a TypeScript build-time error if you did something wrong or the AST changes!
return ((node: never): never => {
throw new Error('Unhandled Node Type in SelectionSetNode.selections');
})(node);
}
});
}
const getEndpointOptions = (
endpoints: RestLink.Endpoints,
endpoint: RestLink.Endpoint,
): RestLink.EndpointOptions => {
const result =
endpoints[endpoint || DEFAULT_ENDPOINT_KEY] ||
endpoints[DEFAULT_ENDPOINT_KEY];
if (typeof result === 'string') {
return { uri: result };
}
return {
responseTransformer: null,
...result,
};
};
/** Replaces params in the path, keyed by colons */
const replaceLegacyParam = (
endpoint: string,
name: string,
value: string,
): string => {
if (value === undefined || name === undefined) {
return endpoint;
}
return endpoint.replace(`:${name}`, value);
};
/** Internal Tool that Parses Paths for RestLink -- This API should be considered experimental */
export class PathBuilder {
/** For accelerating the replacement of paths that are used a lot */
private static cache: {
[path: string]: (props: RestLink.PathBuilderProps) => string;
} = {};
/** Table to limit the amount of nagging (due to probable API Misuse) we do to once per path per launch */
private static warnTable: { [key: string]: true } = {};
/** Regexp that finds things that are eligible for variable replacement */
private static argReplacement = /({[._a-zA-Z0-9]*})/;
static replacerForPath(
path: string,
): (props: RestLink.PathBuilderProps) => string {
if (path in PathBuilder.cache) {
return PathBuilder.cache[path];
}
const queryOrigStartIndex = path.indexOf('?');
const pathBits = path.split(PathBuilder.argReplacement);
const chunkActions: Array<
| true // We're enabling the qs-encoder
| string // This is a raw string bit, don't mess with it
| ((props: RestLink.RestLinkHelperProps, useQSEncoder: boolean) => string)
> = [];
let hasBegunQuery = false;
pathBits.reduce((processedCount, bit) => {
if (bit === '' || bit === '{}') {
// Empty chunk, do nothing
return processedCount + bit.length;
}
const nextIndex = processedCount + bit.length;
if (bit[0] === '{' && bit[bit.length - 1] === '}') {
// Replace some args!
const _keyPath = bit.slice(1, bit.length - 1).split('.');
chunkActions.push(
(props: RestLink.RestLinkHelperProps, useQSEncoder: boolean) => {
try {
const value = PathBuilderLookupValue(props, _keyPath);
if (
!useQSEncoder ||
(typeof value !== 'object' || value == null)
) {
return String(value);
} else {
return qs.stringify(value);
}
} catch (e) {
const key = [path, _keyPath.join('.')].join('|');
if (!(key in PathBuilder.warnTable)) {
console.warn(
'Warning: RestLink caught an error while unpacking',
key,
"This tends to happen if you forgot to pass a parameter needed for creating an @rest(path, or if RestLink was configured to deeply unpack a path parameter that wasn't provided. This message will only log once per detected instance. Trouble-shooting hint: check @rest(path: and the variables provided to this query.",
);
PathBuilder.warnTable[key] = true;
}
return '';
}
},
);
} else {
chunkActions.push(bit);
if (!hasBegunQuery && nextIndex >= queryOrigStartIndex) {
hasBegunQuery = true;
chunkActions.push(true);
}
}
return nextIndex;
}, 0);
const result: (props: RestLink.PathBuilderProps) => string = props => {
let hasEnteredQuery = false;
const tmp = chunkActions.reduce((accumulator: string, action): string => {
if (typeof action === 'string') {
return accumulator + action;
} else if (typeof action === 'boolean') {
hasEnteredQuery = true;
return accumulator;
} else {
return accumulator + action(props, hasEnteredQuery);
}
}, '') as string;
return tmp;
};
return (PathBuilder.cache[path] = result);
}
}
/** Private Helper Function */
function PathBuilderLookupValue(tmp: object, keyPath: string[]) {
if (keyPath.length === 0) {
return tmp;
}
const remainingKeyPath = [...keyPath]; // Copy before mutating
const key = remainingKeyPath.shift();
return PathBuilderLookupValue(tmp[key], remainingKeyPath);
}
/**
* Some keys should be passed through transparently without normalizing/de-normalizing
*/
const noMangleKeys = ['__typename'];
/** Trivial globalThis polyfill that falls-back to our previous global object in case people had polyfilled that */
const globalScope = (typeof globalThis === 'object' && globalThis) || global;
/** Recursively descends the provided object tree and converts all the keys */
const convertObjectKeys = (
object: object,
__converter: RestLink.FieldNameNormalizer,
keypath: string[] = [],
): object => {
let converter: RestLink.FieldNameNormalizer = null;
if (__converter.length != 2) {
converter = (name, keypath) => {
return __converter(name);
};
} else {
converter = __converter;
}
if (Array.isArray(object)) {
return object.map((o, index) =>
convertObjectKeys(o, converter, [...keypath, String(index)]),
);
}
if (
object == null ||
typeof object !== 'object' ||
object.constructor !== Object
) {
// Object is a scalar or null / undefined => no keys to convert!
return object;
}
// FileList/File are only available in some browser contexts
// Notably: *not available* in react-native.
if (
((globalScope as any).FileList && object instanceof FileList) ||
((globalScope as any).File && object instanceof File)
) {
// Object is a FileList or File object => no keys to convert!
return object;
}
return Object.keys(object).reduce((acc: any, key: string) => {
let value = object[key];
if (noMangleKeys.indexOf(key) !== -1) {
acc[key] = value;
return acc;
}
const nestedKeyPath = [...keypath, key];
acc[converter(key, nestedKeyPath)] = convertObjectKeys(
value,
converter,
nestedKeyPath,
);
return acc;
}, {});
};
const noOpNameNormalizer: RestLink.FieldNameNormalizer = (name: string) => {
return name;
};
/**
* Helper that makes sure our headers are of the right type to pass to Fetch
*/
export const normalizeHeaders = (
headers: RestLink.InitializationHeaders,
): Headers => {
// Make sure that our headers object is of the right type
if (headers instanceof Headers) {
return headers;
} else {
return new Headers(headers || {});
}
};
/**
* Returns a new Headers Group that contains all the headers.
* - If there are duplicates, they will be in the returned header set multiple times!
*/
export const concatHeadersMergePolicy: RestLink.HeadersMergePolicy = (
...headerGroups: Headers[]
): Headers => {
return headerGroups.reduce((accumulator, current) => {
if (!current) {
return accumulator;
}
if (!current.forEach) {
current = normalizeHeaders(current);
}
current.forEach((value, key) => {
accumulator.append(key, value);
});
return accumulator;
}, new Headers());
};
/**
* This merge policy deletes any matching headers from the link's default headers.
* - Pass headersToOverride array & a headers arg to context and this policy will automatically be selected.
*/
export const overrideHeadersMergePolicy = (
linkHeaders: Headers,
headersToOverride: string[],
requestHeaders: Headers | null,
): Headers => {
const result = new Headers();
linkHeaders.forEach((value, key) => {
if (headersToOverride.indexOf(key) !== -1) {
return;
}
result.append(key, value);
});
return concatHeadersMergePolicy(result, requestHeaders || new Headers());
};
export const overrideHeadersMergePolicyHelper = overrideHeadersMergePolicy; // Deprecated name
const makeOverrideHeadersMergePolicy = (
headersToOverride: string[],
): RestLink.HeadersMergePolicy => {
return (linkHeaders, requestHeaders) => {
return overrideHeadersMergePolicy(
linkHeaders,
headersToOverride,
requestHeaders,
);
};
};
const SUPPORTED_HTTP_VERBS = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'];
export const validateRequestMethodForOperationType = (
method: string,
operationType: OperationTypeNode,
): void => {
switch (operationType) {
case 'query':
if (SUPPORTED_HTTP_VERBS.indexOf(method.toUpperCase()) !== -1) {
return;
}
throw new Error(
`A "query" operation can only support "GET" requests but got "${method}".`,
);
case 'mutation':
if (SUPPORTED_HTTP_VERBS.indexOf(method.toUpperCase()) !== -1) {
return;
}
throw new Error('"mutation" operations do not support that HTTP-verb');
case 'subscription':
throw new Error('A "subscription" operation is not supported yet.');
default:
const _exhaustiveCheck: never = operationType;
return _exhaustiveCheck;
}
};
/**
* Utility to build & throw a JS Error from a "failed" REST-response
* @param response: HTTP Response object for this request
* @param result: Promise that will render the body of the response
* @param message: Human-facing error message
*/
const rethrowServerSideError = (
response: Response,
result: any,
message: string,
) => {
const error = new Error(message) as RestLink.ServerError;
error.response = response;
error.statusCode = response.status;
error.result = result;
throw error;
};
/** Apollo-Link getContext, provided from the user & mutated by upstream links */
interface LinkChainContext {
/** Credentials Policy for Fetch */
credentials?: RequestCredentials | null;
/** Headers the user wants to set on this request. See also headersMergePolicy */
headers?: RestLink.InitializationHeaders | null;
/** Will default to concatHeadersMergePolicy unless headersToOverride is set */
headersMergePolicy?: RestLink.HeadersMergePolicy | null;
/** List of headers to override, passing this will swap headersMergePolicy if necessary */
headersToOverride?: string[] | null;
/** An array of the responses from each fetched URL, useful for accessing headers in earlier links */
restResponses?: Response[];
}
/** Context passed via graphql() to our resolver */
interface RequestContext {
/** Headers the user wants to set on this request. See also headersMergePolicy */
headers: Headers;
/** Credentials Policy for Fetch */
credentials?: RequestCredentials | null;
/** Exported variables fulfilled in this request, using @export(as:). They are stored keyed by node to support deeply nested structures with exports at multiple levels */
exportVariablesByNode: Map<any, { [key: string]: any }>;
endpoints: RestLink.Endpoints;
customFetch: RestLink.CustomFetch;
operationType: OperationTypeNode;
fieldNameNormalizer: RestLink.FieldNameNormalizer;
fieldNameDenormalizer: RestLink.FieldNameNormalizer;
mainDefinition: OperationDefinitionNode | FragmentDefinitionNode;
fragmentDefinitions: FragmentDefinitionNode[];
typePatcher: RestLink.FunctionalTypePatcher;
serializers: RestLink.Serializers;
responseTransformer: RestLink.ResponseTransformer;
/** An array of the responses from each fetched URL */
responses: Response[];
}
const addTypeToNode = (node, typename) => {
if (node === null || node === undefined || typeof node !== 'object') {
return node;
}
if (!Array.isArray(node)) {
node['__typename'] = typename;
return node;
}
return node.map(item => {
return addTypeToNode(item, typename);
});
};
const resolver: Resolver = async (
fieldName: string,
root: any,
args: any,
context: RequestContext,
info: ExecInfo,
) => {
const { directives, isLeaf, resultKey } = info;
const { exportVariablesByNode } = context;
const exportVariables = exportVariablesByNode.get(root) || {};
/** creates a copy of this node's export variables for its child nodes. iterates over array results to provide for each child. returns the passed result. */
const copyExportVariables = <T>(result: T): T => {
if (result instanceof Array) {
result.forEach(copyExportVariables);
} else {
// export variables are stored keyed on the node they are for
exportVariablesByNode.set(result, { ...exportVariables });
}
return result;
};
// Support GraphQL Aliases!
const aliasedNode = (root || {})[resultKey];
const preAliasingNode = (root || {})[fieldName];
if (root && directives && directives.export) {
// @export(as:) is only supported with apollo-link-rest at this time
// so use the preAliasingNode as we're responsible for implementing aliasing!
exportVariables[directives.export.as] = preAliasingNode;
}
const isATypeCall = directives && directives.type;
if (!isLeaf && isATypeCall) {
// @type(name: ) is only supported inside apollo-link-rest at this time
// so use the preAliasingNode as we're responsible for implementing aliasing!
// Also: exit early, since @type(name: ) && @rest() can't both exist on the same node.
if (directives.rest) {
throw new Error(
'Invalid use of @type(name: ...) directive on a call that also has @rest(...)',
);
}
copyExportVariables(preAliasingNode);
return addTypeToNode(preAliasingNode, directives.type.name);
}
const isNotARestCall = !directives || !directives.rest;
if (isNotARestCall) {
// This is not tagged with @rest()
// This might not belong to us so return the aliasNode version preferentially
return copyExportVariables(aliasedNode || preAliasingNode);
}
const {
credentials,
endpoints,
headers,
customFetch,
operationType,
typePatcher,
mainDefinition,
fragmentDefinitions,
fieldNameNormalizer: linkLevelNameNormalizer,
fieldNameDenormalizer: linkLevelNameDenormalizer,
serializers,
responseTransformer,
} = context;
const fragmentMap = createFragmentMap(fragmentDefinitions);
let {
path,
endpoint,
pathBuilder,
} = directives.rest as RestLink.DirectiveOptions;
const endpointOption = getEndpointOptions(endpoints, endpoint);
const neitherPathsProvided = path == null && pathBuilder == null;
if (neitherPathsProvided) {
throw new Error(
`One of ("path" | "pathBuilder") must be set in the @rest() directive. This request had neither, please add one`,
);
}
if (!pathBuilder) {
if (!path.includes(':')) {
// Colons are the legacy route, and aren't uri encoded anyhow.
pathBuilder = PathBuilder.replacerForPath(path);
} else {
console.warn(
"Deprecated: '@rest(path:' contains a ':' colon, this format will be removed in future versions",
);
pathBuilder = ({
args,
exportVariables,
}: RestLink.PathBuilderProps): string => {
const legacyArgs = {
...args,
...exportVariables,
};
const pathWithParams = Object.keys(legacyArgs).reduce(
(acc, e) => replaceLegacyParam(acc, e, legacyArgs[e]),
path,
);
if (pathWithParams.includes(':')) {
throw new Error(
'Missing parameters to run query, specify it in the query params or use ' +
'an export directive. (If you need to use ":" inside a variable string' +
' make sure to encode the variables properly using `encodeURIComponent' +
'`. Alternatively see documentation about using pathBuilder.)',
);
}
return pathWithParams;
};
}
}
const allParams: RestLink.PathBuilderProps = {
args,
exportVariables,
context,
'@rest': directives.rest,
replacer: pathBuilder,