Last active
September 18, 2017 06:22
-
-
Save ihfazhillah/6289d7958592c055a2cbcad5d3821039 to your computer and use it in GitHub Desktop.
Make an apollo client instance capable of uploading files to Scaphold.io via GraphQL
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import ApolloClient, { createNetworkInterface } from 'apollo-client'; | |
import RecursiveIterator from 'recursive-iterator'; | |
//import fetch from 'node-fetch'; | |
import { print as printGraphQL } from 'graphql-tag/printer'; | |
import _ from lodash; | |
export function makeApolloFileHandler() { | |
const url = `https://us-west-2.api.scaphold.io/graphql/my-awesome-app`; | |
const networkInterface = createNetworkInterface(url); | |
networkInterface.query = (request) => { | |
const formData = new FormData(); | |
// Pull the files out of variables and attach at the root of the multipart/form-data request | |
for (const { node, path } of new RecursiveIterator(request.variables)) { | |
if (node instanceof File) { | |
// const id = Math.random().toString(36); | |
const id = node.name; | |
formData.append(path[1], node); // we need a value of 'blobFieldName' | |
// objectPath.set(request.variables, path.join('.'), id); // dont do this, instead, we must remove this property | |
_.unset(request.variables, path.join('.')) | |
} | |
} | |
formData.append('query', printGraphQL(request.query)); | |
formData.append('variables', JSON.stringify(request.variables || {})); | |
formData.append('debugName', JSON.stringify(request.debugName || '')); | |
formData.append('operationName', JSON.stringify(request.operationName || '')); | |
const headers = { Accept: '*/*' }; | |
if (localStorage.getItem('scaphold_user_token')) { | |
headers.Authorization = `Bearer ${localStorage.getItem('scaphold_user_token')}`; | |
} | |
return fetch(url, { | |
headers, | |
body: formData, | |
method: 'POST', | |
}).then(result => result.json()); | |
}; | |
const apolloClient = new ApolloClient({ | |
networkInterface, | |
initialState: {}, | |
}); | |
return apolloClient; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment