Skip to content

Instantly share code, notes, and snippets.

@rutvikbhatt9
Created January 30, 2023 17:25
Show Gist options
  • Save rutvikbhatt9/0cf94e805cd9b903b284c8f8409bc2fb to your computer and use it in GitHub Desktop.
Save rutvikbhatt9/0cf94e805cd9b903b284c8f8409bc2fb to your computer and use it in GitHub Desktop.
import { ApolloLink, Observable } from "@apollo/client";
const request = async (operation) => {
const token = "yourToken"; // you can get token from persistent storage or redux store
console.log('REQUESTING', operation.operationName, operation.variables);
operation.setContext({
headers: {
authorization: `Bearer ${token}`,
},
});
};
const requestLink = new ApolloLink((operation, forward) => new Observable(observer => {
let handle // ref variable to unsubscribe on dispose
Promise.resolve(operation)
.then(opr => request(opr))
.then(() => {
handle = forward(operation).subscribe({
next: observer.next.bind(observer),
error: observer.error.bind(observer),
complete: observer.complete.bind(observer)
})
})
.catch(observer.error.bind(observer))
return () => {
if (handle) {
handle.unsubscribe()
}
}
}))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment