Hi, unfortunately I need some more explanations, if you could be so kind.
First, as a general question, what is the difference between defining the authLink as newApolloLink and setContext, that is between this two snippets:
const authLink = new ApolloLink((operation, forward) => {
const accessToken = localStorage.getItem("accessToken");
operation.setContext(({ headers }) => ({
headers: {
...headers,
authorization: accessToken ? `Bearer ${accessToken}` : "",
},
}));
return forward(operation);
});
vs
const authLink = setContext((_, { headers }) => {
const accessToken = localStorage.getItem("accessToken");
return {
headers: {
...headers,
authorization: token,
},
};
});
Second, I am in a situation where, when the access token has expired I use the refresh token to ask for a new access token (and refresh token). So this is my implementation of the authLink, errorLink and getNewToken and it would be very helpful you could tell me something since at the moment it is not working
const authLink = setContext((_, { headers }) => {
const token = localStorage.getItem("accessToken");
return {
headers: {
...headers,
authorization: token ? `Bearer ${token}` : "",
},
};
});
const getNewToken = async () => {
try {
const { data } = await axios.post(
"https://fxxxx.ngrok.io/api/v2/refresh",
{ token: localStorage.getItem("refreshToken") }
);
localStorage.setItem("refreshToken", data.refresh_token);
return data.access_token;
} catch (error) {
console.log(error);
}
};
const errorLink = onError(
({ graphQLErrors, networkError, operation, forward }) => {
if (graphQLErrors) {
for (let err of graphQLErrors) {
switch (err.extensions.code) {
case "UNAUTHENTICATED":
return fromPromise(
getNewToken().catch((error) => {
return;
})
)
.filter((value) => Boolean(value))
.flatMap((accessToken) => {
const oldHeaders = operation.getContext().headers;
operation.setContext({
headers: {
...oldHeaders,
authorization: `Bearer ${accessToken}`,
},
});
return forward(operation);
});
}
}
}
}
);
const client = new ApolloClient({
link: from([authLink, errorLink, httpLink]),
cache: new InMemoryCache(),
});