-
-
Notifications
You must be signed in to change notification settings - Fork 155
/
batch-network-interface.js
53 lines (47 loc) · 1.73 KB
/
batch-network-interface.js
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
import { HTTPBatchedNetworkInterface, printAST } from 'apollo-client'
import { extractRequestFiles } from './helpers'
export class HTTPUploadBatchNetworkInterface extends HTTPBatchedNetworkInterface {
batchedFetchFromRemoteEndpoint({ requests, options }) {
// Skip upload proccess if SSR
if (typeof FormData !== 'undefined') {
// Extract any files from the request
const batchFiles = []
const batchOperations = requests.map((request, operationIndex) => {
const { operation, files } = extractRequestFiles(request)
if (files.length) {
batchFiles.push({
operationIndex,
files
})
}
return operation
})
// Only initiate a multipart form request if there are uploads
if (batchFiles.length) {
// For each operation, convert query AST to string for transport
batchOperations.forEach(operation => {
operation.query = printAST(operation.query)
})
// Build the form
const formData = new FormData()
formData.append('operations', JSON.stringify(batchOperations))
batchFiles.forEach(({ operationIndex, files }) => {
files.forEach(({ variablesPath, file }) =>
formData.append(`${operationIndex}.${variablesPath}`, file)
)
})
// Send request
return fetch(this._uri, {
method: 'POST',
body: formData,
...options
})
}
}
// Standard fetch method fallback
return super.batchedFetchFromRemoteEndpoint({ requests, options })
}
}
export function createBatchNetworkInterface({ uri, batchInterval, opts = {} }) {
return new HTTPUploadBatchNetworkInterface(uri, batchInterval, opts)
}