-
Notifications
You must be signed in to change notification settings - Fork 2.9k
Expand file tree
/
Copy pathbatchHttpLink.ts
More file actions
214 lines (186 loc) · 6.53 KB
/
Copy pathbatchHttpLink.ts
File metadata and controls
214 lines (186 loc) · 6.53 KB
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
import { Observable, throwError } from "rxjs";
import { ApolloLink } from "@apollo/client/link";
import { BatchLink } from "@apollo/client/link/batch";
import { ClientAwarenessLink } from "@apollo/client/link/client-awareness";
import type { HttpLink } from "@apollo/client/link/http";
import {
checkFetcher,
defaultPrinter,
fallbackHttpConfig,
parseAndCheckHttpResponse,
selectHttpOptionsAndBodyInternal,
selectURI,
} from "@apollo/client/link/http";
import { filterOperationVariables } from "@apollo/client/link/utils";
import { __DEV__ } from "@apollo/client/utilities/environment";
import { compact } from "@apollo/client/utilities/internal";
import { maybe } from "@apollo/client/utilities/internal/globals";
export declare namespace BatchHttpLink {
export type Options = Pick<
BatchLink.Options,
"batchMax" | "batchDebounce" | "batchInterval" | "batchKey"
> &
Omit<HttpLink.Options, "useGETForQueries">;
export type ContextOptions = HttpLink.ContextOptions;
}
const backupFetch = maybe(() => fetch);
/**
* Transforms Operation for into HTTP results.
* context can include the headers property, which will be passed to the fetch function
*/
export class BatchHttpLink extends ApolloLink {
constructor(
options: BatchHttpLink.Options & ClientAwarenessLink.Options = {}
) {
const { left, right, request } = ApolloLink.from([
new ClientAwarenessLink(options),
new BaseBatchHttpLink(options),
]);
super(request);
Object.assign(this, { left, right });
}
}
export class BaseBatchHttpLink extends ApolloLink {
private batchDebounce?: boolean;
private batchInterval: number;
private batchMax: number;
private batcher: ApolloLink;
constructor(fetchParams?: BatchHttpLink.Options) {
super();
let {
uri = "/graphql",
// use default global fetch if nothing is passed in
fetch: preferredFetch,
print = defaultPrinter,
includeExtensions,
preserveHeaderCase,
batchInterval,
batchDebounce,
batchMax,
batchKey,
includeUnusedVariables = false,
...requestOptions
} = fetchParams || ({} as BatchHttpLink.Options);
if (__DEV__) {
// Make sure at least one of preferredFetch, window.fetch, or backupFetch
// is defined, so requests won't fail at runtime.
checkFetcher(preferredFetch || backupFetch);
}
const linkConfig = {
http: compact({ includeExtensions, preserveHeaderCase }),
options: requestOptions.fetchOptions,
credentials: requestOptions.credentials,
headers: requestOptions.headers,
};
this.batchDebounce = batchDebounce;
this.batchInterval = batchInterval || 10;
this.batchMax = batchMax || 10;
const batchHandler: BatchLink.BatchHandler = (operations) => {
const chosenURI = selectURI(operations[0], uri);
const context = operations[0].getContext();
const contextConfig = {
http: context.http,
options: context.fetchOptions,
credentials: context.credentials,
headers: context.headers,
};
//uses fallback, link, and then context to build options
const optsAndBody = operations.map((operation) => {
const result = selectHttpOptionsAndBodyInternal(
operation,
print,
fallbackHttpConfig,
linkConfig,
contextConfig
);
if (result.body.variables && !includeUnusedVariables) {
result.body.variables = filterOperationVariables(
result.body.variables,
operation.query
);
}
return result;
});
const loadedBody = optsAndBody.map(({ body }) => body);
const options = optsAndBody[0].options;
// There's no spec for using GET with batches.
if (options.method === "GET") {
return throwError(
() =>
new Error("apollo-link-batch-http does not support GET requests")
);
}
try {
(options as any).body = JSON.stringify(loadedBody);
} catch (parseError) {
return throwError(() => parseError);
}
let controller: AbortController | undefined;
if (!options.signal && typeof AbortController !== "undefined") {
controller = new AbortController();
options.signal = controller.signal;
}
return new Observable((observer) => {
// Prefer BatchHttpLink.Options.fetch (preferredFetch) if provided, and
// otherwise fall back to the *current* global window.fetch function
// (see issue #7832), or (if all else fails) the backupFetch function we
// saved when this module was first evaluated. This last option protects
// against the removal of window.fetch, which is unlikely but not
// impossible.
const currentFetch =
preferredFetch || maybe(() => fetch) || backupFetch;
currentFetch!(chosenURI, options)
.then((response) => {
// Make the raw response available in the context.
operations.forEach((operation) =>
operation.setContext({ response })
);
return response;
})
.then(parseAndCheckHttpResponse(operations))
.then((result) => {
controller = undefined;
// we have data and can send it to back up the link chain
observer.next(result);
observer.complete();
return result;
})
.catch((err) => {
controller = undefined;
observer.error(err);
});
return () => {
// XXX support canceling this request
// https://developers.google.com/web/updates/2017/09/abortable-fetch
if (controller) controller.abort();
};
});
};
batchKey =
batchKey ||
((operation: ApolloLink.Operation) => {
const context = operation.getContext();
const contextConfig = {
http: context.http,
options: context.fetchOptions,
credentials: context.credentials,
headers: context.headers,
};
//may throw error if config not serializable
return selectURI(operation, uri) + JSON.stringify(contextConfig);
});
this.batcher = new BatchLink({
batchDebounce: this.batchDebounce,
batchInterval: this.batchInterval,
batchMax: this.batchMax,
batchKey,
batchHandler,
});
}
public request(
operation: ApolloLink.Operation,
forward: ApolloLink.ForwardFunction
): Observable<ApolloLink.Result> {
return this.batcher.request(operation, forward);
}
}