1 | ;
|
2 |
|
3 | const extractFiles = require('extract-files/public/extractFiles');
|
4 |
|
5 | /**
|
6 | * Creates default [`fetch` options]{@link FetchOptions} for a
|
7 | * [GraphQL operation]{@link GraphQLOperation}. If the
|
8 | * [GraphQL operation]{@link GraphQLOperation} contains files to upload, the
|
9 | * options will be for a
|
10 | * [GraphQL multipart request](https://github.com/jaydenseric/graphql-multipart-request-spec),
|
11 | * otherwise they will be for a regular
|
12 | * [GraphQL `POST` request](https://github.com/graphql/graphql-over-http/blob/main/spec/GraphQLOverHTTP.md#post).
|
13 | *
|
14 | * This utility exists for user convenience and isn’t used directly by the
|
15 | * `graphql-react` API. If there is no chance the
|
16 | * [GraphQL operation]{@link GraphQLOperation} contains files, avoid using this
|
17 | * utility for a smaller bundle size.
|
18 | * @kind function
|
19 | * @name fetchOptionsGraphQL
|
20 | * @param {GraphQLOperation} operation GraphQL operation.
|
21 | * @returns {FetchOptions} [`fetch`](https://developer.mozilla.org/docs/Web/API/Fetch_API) options.
|
22 | * @example <caption>Ways to `import`.</caption>
|
23 | * ```js
|
24 | * import { fetchOptionsGraphQL } from 'graphql-react';
|
25 | * ```
|
26 | *
|
27 | * ```js
|
28 | * import fetchOptionsGraphQL from 'graphql-react/public/fetchOptionsGraphQL.js';
|
29 | * ```
|
30 | * @example <caption>Ways to `require`.</caption>
|
31 | * ```js
|
32 | * const { fetchOptionsGraphQL } = require('graphql-react');
|
33 | * ```
|
34 | *
|
35 | * ```js
|
36 | * const fetchOptionsGraphQL = require('graphql-react/public/fetchOptionsGraphQL');
|
37 | * ```
|
38 | */
|
39 | module.exports = function fetchOptionsGraphQL(operation) {
|
40 | const fetchOptions = {
|
41 | method: 'POST',
|
42 | headers: { Accept: 'application/json' },
|
43 | };
|
44 |
|
45 | const { clone, files } = extractFiles(operation);
|
46 | const operationJSON = JSON.stringify(clone);
|
47 |
|
48 | if (files.size) {
|
49 | // See the GraphQL multipart request spec:
|
50 | // https://github.com/jaydenseric/graphql-multipart-request-spec
|
51 |
|
52 | const form = new FormData();
|
53 |
|
54 | form.set('operations', operationJSON);
|
55 |
|
56 | const map = {};
|
57 | let i = 0;
|
58 | files.forEach((paths) => {
|
59 | map[++i] = paths;
|
60 | });
|
61 | form.set('map', JSON.stringify(map));
|
62 |
|
63 | i = 0;
|
64 | files.forEach((paths, file) => {
|
65 | form.set(`${++i}`, file, file.name);
|
66 | });
|
67 |
|
68 | fetchOptions.body = form;
|
69 | } else {
|
70 | fetchOptions.headers['Content-Type'] = 'application/json';
|
71 | fetchOptions.body = operationJSON;
|
72 | }
|
73 |
|
74 | return fetchOptions;
|
75 | };
|