import { ApolloClient, createHttpLink, InMemoryCache } from '@apollo/client';
import { setContext } from '@apollo/client/link/context';
const httpLink = createHttpLink({
uri: '/graphql',
});
const authLink = setContext((_, { headers }) => {
// get the authentication token from local storage if it exists
const token = localStorage.getItem('token');
// return the headers to the context so httpLink can read them
return {
headers: {
...headers,
authorization: token ? `Bearer ${token}` : "",
}
}
});
const client = new ApolloClient({
link: authLink.concat(httpLink),
cache: new InMemoryCache()
});
import { setContext } from "apollo-link-context";
import { onError } from "apollo-link-error";
// cached storage for the user token
// cached storage for the user token
let token;
const withToken = setContext(() => {
// if you have a cached value, return it immediately
// if you have a cached value, return it immediately
if (token) return { token };
return AsyncTokenLookup().then(userToken => {
token = userToken;
return { token };
});
});
const resetToken = onError(({ networkError }) => {
if (networkError && networkError.name ==='ServerError' && networkError.statusCode === 401) {
// remove cached token on 401 from the server
// remove cached token on 401 from the server
token = null;
}
});
const authFlowLink = withToken.concat(resetToken);
import { setContext } from "@apollo/client/link/context";
import { onError } from "@apollo/client/link/error";
// cached storage for the user token
let token;
const withToken = setContext(() => {
// if you have a cached value, return it immediately
if (token) return { token };
return AsyncTokenLookup().then(userToken => {
token = userToken;
return { token };
});
});
const resetToken = onError(({ networkError }) => {
if (
networkError &&
networkError.name ==='ServerError' &&
networkError.statusCode === 401
) {
// remove cached token on 401 from the server
token = null;
}
});
const authFlowLink = withToken.concat(resetToken);
import { setContext } from "apollo-link-context";
const setAuthorizationLink = setContext((request, previousContext) => ({
headers: {authorization: "1234"}
}));
const asyncAuthLink = setContext(
request =>
new Promise((success, fail) => {
// do some async lookup here
// do some async lookup here
setTimeout(() => {
success({ token: "async found token" });
}, 10);
})
);
import { setContext } from "@apollo/client/link/context";
const setAuthorizationLink = setContext((request, previousContext) => ({
headers: {authorization: "1234"}
}));
const asyncAuthLink = setContext(
request =>
new Promise((success, fail) => {
// do some async lookup here
setTimeout(() => {
success({ token: "async found token" });
}, 10);
})
);