Skip to content

Instantly share code, notes, and snippets.

@danielbuechele
Last active June 19, 2019 23:29
Show Gist options
  • Save danielbuechele/77bb8d931de30d04c1e7e23ebbcfe45d to your computer and use it in GitHub Desktop.
Save danielbuechele/77bb8d931de30d04c1e7e23ebbcfe45d to your computer and use it in GitHub Desktop.
import { print as printGraphQL } from 'graphql-tag/printer';
import RecursiveIterator from 'recursive-iterator';
import objectPath from 'object-path';
export function createNetworkInterface(url) {
return {
query(request) {
const formData = new FormData();
// search for File objects on the request and set it as formData
for(let { node, path } of new RecursiveIterator(request.variables)) {
if (node instanceof File) {
const id = Math.random().toString(36);
formData.append(id, node);
objectPath.set(request.variables, path.join('.'), id);
}
}
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 || ''));
return fetch(url, {
headers: { Accept: '*/*' },
body: formData,
method: 'POST',
}).then(result => result.json());
}
}
}
@andevsoftware
Copy link

Thanks for your example, JSON.stringify around the operationName is redundant. Will give an error.

 formData.append('operationName', JSON.stringify(request.operationName || ''));

to

 formData.append('operationName', request.operationName);

@aaronksaunders
Copy link

does this still work with the latest version of the Apollo client?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment