Async Middleware (with ApolloLink)
See original GitHub issueIntended outcome:
To resolve a promise inside an ApolloLink
middleware to adjust request headers.
Actual outcome:
Wasn’t able to write code that works.
How to reproduce the issue:
import { ApolloLink } from 'apollo-client-preset'
export const authMiddleware = new ApolloLink((operation, forward) => {
resolvePromise().then(data => {
operation.setContext(({ headers = {} }) => ({
headers: {
...headers,
authorization: || null,
}
}))
return forward(operation)
})
})
There’s no examples regarding this type of middleware in the docs. How can this be achieved?
Version
- apollo-client@^2.0.1
Issue Analytics
- State:
- Created 6 years ago
- Comments:34 (2 by maintainers)
Top Results From Across the Web
Apollo HttpLink Async - Stack Overflow
You can use apollo-link-context to modify your requests. You can cache the values as shown if you don't fetch them on every request....
Read more >Advanced HTTP networking - Apollo GraphQL Docs
Take full network control with Apollo Link. The Apollo Link library gives you fine-grained control of HTTP requests that are sent by Apollo...
Read more >How to use the apollo-link.from function in apollo-link - Snyk
To help you get started, we've selected a few apollo-link.from examples, ... ApolloClient({ link: from([Middleware, Afterware, errorLink, httpLink]), cache, ...
Read more >Apollo GraphQL : Async Access Token Refresh - Able
We'll be using the fromPromise utility function from the apollo-link package to transform our Promise to an Observable.
Read more >apollo-link.Operation.setContext JavaScript and Node.js code ...
function createClient(headers, token, initialState) { let accessToken = token; (async () => { // eslint-disable-next-line no-param-reassign accessToken ...
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
@pycraft114 @matteodem Here is how I got it working:
@jbaxleyiii The documentation was a little confusing due to not having a fully working example with the HTTP link. I understand this is meant to be generalized for any link, but your advice in this issue was a little misleading due to having to set explicitly structure the context to what HttpLink expects. How can we make the documentation clearer in the migration and other related documentations?
Following the @vtsatskin’s implementation, I’ve changed the
authMiddleware
function to works withasync/await
.