Created
January 30, 2023 17:25
-
-
Save rutvikbhatt9/0cf94e805cd9b903b284c8f8409bc2fb to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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