https://github.com/relay-tools/fetch-multipart-graphql
Cross browser function to fetch and parse streaming multipart graphql responses
https://github.com/relay-tools/fetch-multipart-graphql
Last synced: 11 months ago
JSON representation
Cross browser function to fetch and parse streaming multipart graphql responses
- Host: GitHub
- URL: https://github.com/relay-tools/fetch-multipart-graphql
- Owner: relay-tools
- License: mit
- Created: 2018-08-06T15:04:09.000Z (over 7 years ago)
- Default Branch: master
- Last Pushed: 2025-03-17T18:03:18.000Z (12 months ago)
- Last Synced: 2025-03-29T19:01:08.987Z (11 months ago)
- Language: JavaScript
- Size: 529 KB
- Stars: 50
- Watchers: 8
- Forks: 9
- Open Issues: 7
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
- awesome-list - fetch-multipart-graphql - tools | 39 | (JavaScript)
README
# fetch-multipart-graphql
Cross-browser function to fetch and parse streaming multipart graphql responses.
This allows you to efficiently fetch streamed GraphQL responses that use the @defer directive as supported by [Apollo Server](https://blog.apollographql.com/introducing-defer-in-apollo-server-f6797c4e9d6e). It can be easily used in a Relay Modern network layer to support deferred queries.
## Usage
In a Relay Network Layer:
```javascript
import fetchMultipart from 'fetch-multipart-graphql';
import { Observable } from 'relay-runtime';
function fetchQuery(operation, variables) {
return Observable.create(sink => {
fetchMultipart('/graphql', {
method: 'POST',
headers: {
'content-type': 'application/json',
},
body: JSON.stringify({
query: operation.text,
variables,
}),
credentials: 'same-origin',
onNext: parts => sink.next(parts),
onError: err => sink.error(err),
onComplete: () => sink.complete(),
});
});
}
```
#### Handling cookies and other auth headers
The `credentials` param is passed to [`fetch`](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters). For XHR requests, [`XMLHttpRequest.withCredentials`](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/withCredentials) is mapped to true when `credentials: 'include'`.
#### Handling additional request settings
When `fetch` is not available requests are sent through XHR, which supports standard `method`, `headers`, `credentials` and `body` settings; as seen in the code example above.
When requests are sent through `fetch` we can also set, in addition to the properties already mentioned, all the [options supported by fetch](https://developer.mozilla.org/en-US/docs/Web/API/fetch#options).
## Browser Support
Tested in the latest Chrome, Firefox, Safari, Edge, and Internet Explorer 11. Requires a polyfill for TextEncoder/Decoder. Since only utf-8 encoding is required, it's recommended to use [text-encoding-utf-8](https://www.npmjs.com/package/text-encoding-utf-8) to minimize impact on bundle size.