kandimat/redaktions-app/src/backend/helper.ts
2021-02-07 23:06:58 +01:00

38 lines
1,020 B
TypeScript

import { ApolloClient, createHttpLink, InMemoryCache } from "@apollo/client";
import { setContext } from "@apollo/client/link/context";
import { getRawJsonWebToken, logoutUser } from "../jwt/jwt";
import { onError } from "@apollo/client/link/error";
import { ServerError } from "@apollo/client/link/utils";
import { ServerParseError } from "@apollo/client/link/http";
const httpLink = createHttpLink({
uri: "http://localhost:5433/graphql",
});
const errorLink = onError(({ networkError }) => {
if (
networkError &&
(networkError as ServerError | ServerParseError).statusCode === 401
) {
logoutUser();
}
});
const authLink = setContext((_, { headers }) => {
const token = getRawJsonWebToken();
return token
? {
headers: {
...headers,
authorization: `Bearer ${token}`,
},
}
: headers;
});
export const client = new ApolloClient({
cache: new InMemoryCache(),
link: errorLink.concat(authLink.concat(httpLink)),
connectToDevTools: true,
});