Skip to content

Commit 4d612f8

Browse files
authored
Merge pull request #189 from D1no/patch-1
Docs: Add customFetch usage example. Closes #184
2 parents 1d04c5c + dc5f531 commit 4d612f8

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

Diff for: docs/rest.md

+33
Original file line numberDiff line numberDiff line change
@@ -339,6 +339,39 @@ const link = new RestLink({
339339

340340
> When using the object form, the `uri` field is required.
341341
342+
<h3 id=options.example.customFetch>Custom Fetch</h3>
343+
344+
By default, Apollo uses the browsers `fetch` method to handle `REST` requests to your domain/endpoint. The `customFetch` option allows you to specify _your own_ request handler by defining a function that returns a `Promise` with a fetch-response-like object:
345+
```js
346+
const link = new RestLink({
347+
endpoints: "/api",
348+
customFetch: (uri, options) => new Promise((resolve, reject) => {
349+
// Your own (asynchronous) request handler
350+
resolve(responseObject)
351+
}),
352+
});
353+
```
354+
355+
To resolve your GraphQL queries quickly, Apollo will issue requests to relevant endpoints as soon as possible. This is generally ok, but can lead to large numbers of `REST` requests to be fired at once; especially for deeply nested queries [(see `@export` directive)](#export).
356+
357+
> Some endpoints (like public APIs) might enforce _rate limits_, leading to failed responses and unresolved queries in such cases.
358+
359+
By example, `customFetch` is a good place to manage your apps fetch operations. The following implementation makes sure to only issue 2 requests at a time (concurrency) while waiting at least 500ms until the next batch of requests is fired.
360+
```js
361+
import pThrottle from "p-throttle";
362+
363+
const link = new RestLink({
364+
endpoints: "/api",
365+
customFetch: pThrottle((uri, config) => {
366+
return fetch(uri, config);
367+
},
368+
2, // Max. concurrent Requests
369+
500 // Min. delay between calls
370+
),
371+
});
372+
```
373+
> Since Apollo issues `Promise` based requests, we can resolve them as we see fit. This example uses [`pThrottle`](https://github.com/sindresorhus/p-throttle); part of the popular [promise-fun](https://github.com/sindresorhus/promise-fun) collection.
374+
342375
<h3 id=options.example>Complete options</h3>
343376

344377
Here is one way you might customize `RestLink`:

0 commit comments

Comments
 (0)