-
-
Notifications
You must be signed in to change notification settings - Fork 154
Expand file tree
/
Copy pathUploadHttpLink.mjs
More file actions
310 lines (280 loc) · 11.3 KB
/
Copy pathUploadHttpLink.mjs
File metadata and controls
310 lines (280 loc) · 11.3 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
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
// @ts-check
/** @import { BaseHttpLink } from "@apollo/client/link/http" */
import { ApolloLink } from "@apollo/client/link";
import {
defaultPrinter,
fallbackHttpConfig,
parseAndCheckHttpResponse,
rewriteURIForGET,
selectHttpOptionsAndBodyInternal,
selectURI,
} from "@apollo/client/link/http";
import { filterOperationVariables } from "@apollo/client/link/utils";
import extractFiles from "extract-files/extractFiles.mjs";
import { Observable } from "rxjs/internal/Observable";
import formDataAppendFile from "./formDataAppendFile.mjs";
import isExtractableFile from "./isExtractableFile.mjs";
/**
* A
* [terminating Apollo Link](https://www.apollographql.com/docs/react/api/link/introduction#the-terminating-link)
* for [Apollo Client](https://www.apollographql.com/docs/react) that fetches a
* [GraphQL multipart request](https://github.com/jaydenseric/graphql-multipart-request-spec)
* if the GraphQL variables contain files (by default
* [`FileList`](https://developer.mozilla.org/en-US/docs/Web/API/FileList),
* [`File`](https://developer.mozilla.org/en-US/docs/Web/API/File), or
* [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob) instances),
* or else fetches a regular
* [GraphQL POST or GET request](https://www.apollographql.com/docs/apollo-server/workflow/requests)
* (depending on the config and GraphQL operation).
*
* Some of the options are similar to the
* [`BaseHttpLink` options](https://www.apollographql.com/docs/react/api/link/apollo-link-base-http#basehttplinkoptions).
* @see [GraphQL multipart request spec](https://github.com/jaydenseric/graphql-multipart-request-spec).
* @example
* A basic Apollo Client setup:
*
* ```js
* import { InMemoryCache } from "@apollo/client/cache";
* import { ApolloClient } from "@apollo/client/core";
* import UploadHttpLink from "apollo-upload-client/UploadHttpLink.mjs";
*
* const client = new ApolloClient({
* cache: new InMemoryCache(),
* link: new UploadHttpLink(),
* });
* ```
*/
export default class UploadHttpLink extends ApolloLink {
/**
* @param {object} options Options.
* @param {Parameters<typeof selectURI>[1]} [options.uri] GraphQL endpoint
* URI. Defaults to `"/graphql"`.
* @param {boolean} [options.useGETForQueries] Should GET be used to fetch
* queries, if there are no files to upload.
* @param {ExtractableFileMatcher} [options.isExtractableFile] Matches
* extractable files in the GraphQL operation. Defaults to
* {@linkcode isExtractableFile}.
* @param {typeof FormData} [options.FormData]
* [`FormData`](https://developer.mozilla.org/en-US/docs/Web/API/FormData)
* class. Defaults to the {@linkcode FormData} global.
* @param {FormDataFileAppender} [options.formDataAppendFile]
* Customizes how extracted files are appended to the
* [`FormData`](https://developer.mozilla.org/en-US/docs/Web/API/FormData)
* instance. Defaults to {@linkcode formDataAppendFile}.
* @param {BaseHttpLink.Printer} [options.print] Prints the GraphQL query or
* mutation AST to a string for transport. Defaults to
* {@linkcode defaultPrinter}.
* @param {typeof fetch} [options.fetch]
* [`fetch`](https://fetch.spec.whatwg.org) implementation. Defaults to the
* {@linkcode fetch} global.
* @param {RequestInit} [options.fetchOptions] `fetch` options; overridden by
* upload requirements.
* @param {string} [options.credentials] Overrides
* {@linkcode RequestInit.credentials credentials} in
* {@linkcode fetchOptions}.
* @param {{ [headerName: string]: string }} [options.headers] Merges with and
* overrides {@linkcode RequestInit.headers headers} in
* {@linkcode fetchOptions}.
* @param {boolean} [options.includeExtensions] Toggles sending `extensions`
* fields to the GraphQL server. Defaults to `false`.
* @param {boolean} [options.includeUnusedVariables] Toggles including unused
* GraphQL variables in the request. Defaults to `false`.
*/
constructor({
uri: fetchUri = "/graphql",
useGETForQueries,
isExtractableFile: customIsExtractableFile = isExtractableFile,
FormData: CustomFormData,
formDataAppendFile: customFormDataAppendFile = formDataAppendFile,
print = defaultPrinter,
fetch: customFetch,
fetchOptions,
credentials,
headers,
includeExtensions,
includeUnusedVariables = false,
} = {}) {
super(
(operation) =>
new Observable((observer) => {
const context = operation.getContext();
const { options, body } = selectHttpOptionsAndBodyInternal(
operation,
print,
fallbackHttpConfig,
{
http: {
includeExtensions,
},
options: fetchOptions,
credentials,
headers,
},
{
http: context.http,
options: context.fetchOptions,
credentials: context.credentials,
headers: context.headers,
},
);
if (body.variables && !includeUnusedVariables)
body.variables = filterOperationVariables(
body.variables,
operation.query,
);
const { clone, files } = extractFiles(
body,
customIsExtractableFile,
"",
);
/**
* URI for the GraphQL request.
* @type {string}
*/
let uri = selectURI(operation, fetchUri);
if (files.size) {
if (options.headers)
// Automatically set by `fetch` when the `body` is a `FormData`
// instance.
delete options.headers["content-type"];
// GraphQL multipart request spec:
// https://github.com/jaydenseric/graphql-multipart-request-spec
const RuntimeFormData = CustomFormData || FormData;
const form = new RuntimeFormData();
form.append("operations", JSON.stringify(clone));
/** @type {{ [key: string]: Array<string> }} */
const map = {};
let i = 0;
files.forEach((paths) => {
map[++i] = paths;
});
form.append("map", JSON.stringify(map));
i = 0;
files.forEach((_paths, file) => {
customFormDataAppendFile(form, String(++i), file);
});
options.body = form;
} else {
if (
useGETForQueries &&
// If the operation contains some mutations GET shouldn’t be used.
!operation.query.definitions.some(
(definition) =>
definition.kind === "OperationDefinition" &&
definition.operation === "mutation",
)
)
options.method = "GET";
if (options.method === "GET") {
const result =
/** @type {{ newURI: string } | { parseError: unknown }} */ (
// The return type is incorrect; `newURI` and `parseError`
// will never both be present.
rewriteURIForGET(uri, body)
);
if ("parseError" in result) throw result.parseError;
uri = result.newURI;
} else options.body = JSON.stringify(clone);
}
/**
* Abort controller for the GraphQL request.
* @type {AbortController}
*/
let controller;
if (typeof AbortController !== "undefined") {
controller = new AbortController();
if (options.signal)
// Respect the user configured abort controller signal.
options.signal.aborted
? // Signal already aborted, so immediately abort.
controller.abort()
: // Signal not already aborted, so setup a listener to abort
// when it does.
options.signal.addEventListener(
"abort",
() => {
controller.abort();
},
{
// Prevent a memory leak if the user configured abort
// controller is long lasting, or controls multiple
// things.
once: true,
},
);
options.signal = controller.signal;
}
/**
* Fetcher for the GraphQL request. Determined when fetching instead
* of when constructing the link to allow more time for instrumenting
* the global `fetch`.
* @see https://github.com/apollographql/apollo-client/issues/7832
*/
const runtimeFetch = customFetch || fetch;
/**
* Is the observable being cleaned up.
* @type {boolean}
*/
let cleaningUp;
runtimeFetch(uri, options)
.then((response) => {
// Forward the response on the context.
operation.setContext({ response });
return response;
})
.then(parseAndCheckHttpResponse(operation))
.then((result) => {
observer.next(result);
observer.complete();
})
.catch((error) => {
// If the observable is being cleaned up, there is no need to call
// next or error because there are no more subscribers. An error
// after cleanup begins is likely from the cleanup function
// aborting the fetch.
if (!cleaningUp) observer.error(error);
});
// Cleanup function.
return () => {
cleaningUp = true;
// Abort fetch. It’s ok to signal an abort even when not fetching.
if (controller) controller.abort();
};
}),
);
}
}
/**
* Checks if a value is an extractable file.
* @template [ExtractableFile=any] Extractable file.
* @callback ExtractableFileMatcher
* @param {unknown} value Value to check.
* @returns {value is ExtractableFile} Is the value an extractable file.
* @example
* How to check for the default exactable files, as well as a custom type of
* file:
*
* ```js
* import isExtractableFile from "apollo-upload-client/isExtractableFile.mjs";
*
* const isExtractableFileEnhanced = (value) =>
* isExtractableFile(value) ||
* (typeof CustomFile !== "undefined" && value instanceof CustomFile);
* ```
*/
/**
* Appends a file extracted from the GraphQL operation to the
* [`FormData`](https://developer.mozilla.org/en-US/docs/Web/API/FormData)
* instance used as the
* [`fetch`](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch)
* `options.body` for the
* [GraphQL multipart request](https://github.com/jaydenseric/graphql-multipart-request-spec).
* @template [ExtractableFile=any] Extractable file.
* @callback FormDataFileAppender
* @param {FormData} formData
* [`FormData`](https://developer.mozilla.org/en-US/docs/Web/API/FormData)
* instance to append the specified file to.
* @param {string} fieldName Form data field name to append the file with.
* @param {ExtractableFile} file File to append. The file type depends on what
* the extractable file matcher extracts.
*/