forked from jaydenseric/apollo-upload-client
-
Notifications
You must be signed in to change notification settings - Fork 0
/
createUploadLink.mjs
301 lines (272 loc) · 11.1 KB
/
createUploadLink.mjs
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
// @ts-check
import { ApolloLink } from "@apollo/client/link/core/ApolloLink.js";
import { createSignalIfSupported } from "@apollo/client/link/http/createSignalIfSupported.js";
import { parseAndCheckHttpResponse } from "@apollo/client/link/http/parseAndCheckHttpResponse.js";
import { rewriteURIForGET } from "@apollo/client/link/http/rewriteURIForGET.js";
import {
defaultPrinter,
fallbackHttpConfig,
selectHttpOptionsAndBodyInternal,
} from "@apollo/client/link/http/selectHttpOptionsAndBody.js";
import { selectURI } from "@apollo/client/link/http/selectURI.js";
import { serializeFetchParameter } from "@apollo/client/link/http/serializeFetchParameter.js";
import { Observable } from "@apollo/client/utilities/observables/Observable.js";
import extractFiles from "extract-files/extractFiles.mjs";
import formDataAppendFile from "./formDataAppendFile.mjs";
import isExtractableFile from "./isExtractableFile.mjs";
/**
* Creates 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
* [`createHttpLink` options](https://www.apollographql.com/docs/react/api/link/apollo-link-http/#httplink-constructor-options).
* @see [GraphQL multipart request spec](https://github.com/jaydenseric/graphql-multipart-request-spec).
* @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 {import("@apollo/client/link/http/selectHttpOptionsAndBody.js").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`.
* @returns A [terminating Apollo Link](https://www.apollographql.com/docs/react/api/link/introduction/#the-terminating-link).
* @example
* A basic Apollo Client setup:
*
* ```js
* import { ApolloClient, InMemoryCache } from "@apollo/client";
* import createUploadLink from "apollo-upload-client/createUploadLink.mjs";
*
* const client = new ApolloClient({
* cache: new InMemoryCache(),
* link: createUploadLink(),
* });
* ```
*/
export default function createUploadLink({
uri: fetchUri = "/graphql",
useGETForQueries,
isExtractableFile: customIsExtractableFile = isExtractableFile,
FormData: CustomFormData,
formDataAppendFile: customFormDataAppendFile = formDataAppendFile,
print = defaultPrinter,
fetch: customFetch,
fetchOptions,
credentials,
headers,
includeExtensions,
} = {}) {
const linkConfig = {
http: { includeExtensions },
options: fetchOptions,
credentials,
headers,
};
return new ApolloLink((operation) => {
const context =
/**
* @type {import("@apollo/client/core/types.js").DefaultContext & {
* clientAwareness?: {
* name?: string,
* version?: string,
* },
* }}
*/
(operation.getContext());
const {
// Apollo Studio client awareness `name` and `version` can be configured
// via `ApolloClient` constructor options:
// https://www.apollographql.com/docs/graphos/metrics/client-awareness/#setup
clientAwareness: { name, version } = {},
headers,
} = context;
const contextConfig = {
http: context.http,
options: context.fetchOptions,
credentials: context.credentials,
headers: {
// Client awareness headers can be overridden by context `headers`.
...(name && { "apollographql-client-name": name }),
...(version && { "apollographql-client-version": version }),
...headers,
},
};
const { options, body } = selectHttpOptionsAndBodyInternal(
operation,
print,
fallbackHttpConfig,
linkConfig,
contextConfig,
);
const { clone, files } = extractFiles(body, customIsExtractableFile, "");
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", serializeFetchParameter(clone, "Payload"));
/** @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 { newURI, parseError } = rewriteURIForGET(uri, body);
if (parseError)
// Apollo’s `HttpLink` uses `fromError` for this, but it’s not
// exported from `@apollo/client/link/http`.
return new Observable((observer) => {
observer.error(parseError);
});
uri = newURI;
} else options.body = serializeFetchParameter(clone, "Payload");
}
const { controller } = createSignalIfSupported();
if (typeof controller !== "boolean") {
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;
}
const runtimeFetch = customFetch || fetch;
return new Observable((observer) => {
/**
* 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) {
// For errors such as an invalid fetch URI there will be no GraphQL
// result with errors or data to forward.
if (error.result && error.result.errors && error.result.data)
observer.next(error.result);
observer.error(error);
}
});
// Cleanup function.
return () => {
cleaningUp = true;
// Abort fetch. It’s ok to signal an abort even when not fetching.
if (typeof controller !== "boolean") 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.
*/