add two libs: graphql and tokenstorage

This commit is contained in:
Dawid Wysokiński 2021-03-07 14:46:37 +01:00
parent 4c64bc70a5
commit 0ea3eb8b07
4 changed files with 87 additions and 0 deletions

2
src/config/api.ts Normal file
View File

@ -0,0 +1,2 @@
export const API_URI =
process.env.REACT_APP_API_URI ?? "http://localhost:8080/graphql";

View File

@ -0,0 +1,39 @@
import {
ApolloClient,
InMemoryCache,
NormalizedCacheObject,
ApolloLink,
} from "@apollo/client";
import { createUploadLink } from "apollo-upload-client";
import { onError } from "@apollo/client/link/error";
import createAuthMiddleware from "./links/authMiddleware";
import TokenStorage from "libs/tokenstorage/TokenStorage";
const createClient = (
uri: string,
tokenStorage: TokenStorage
): ApolloClient<NormalizedCacheObject> => {
return new ApolloClient({
queryDeduplication: true,
cache: new InMemoryCache(),
link: ApolloLink.from([
createAuthMiddleware(tokenStorage),
onError(({ graphQLErrors, networkError }) => {
if (process.env.NODE_ENV === "development") {
if (graphQLErrors)
graphQLErrors.map(({ message, locations, path }) =>
console.log(
`[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`
)
);
if (networkError) console.log(`[Network error]: ${networkError}`);
}
}),
createUploadLink({
uri,
}),
]),
});
};
export default createClient;

View File

@ -0,0 +1,17 @@
import { ApolloLink, NextLink, Operation } from "@apollo/client";
import TokenStorage from "libs/tokenstorage/TokenStorage";
const createAuthMiddleware = (tokenStorage: TokenStorage) => {
return new ApolloLink((operation: Operation, forward: NextLink) => {
if (tokenStorage.token) {
operation.setContext({
headers: {
Authorization: "Bearer " + tokenStorage.token,
},
});
}
return forward(operation);
});
};
export default createAuthMiddleware;

View File

@ -0,0 +1,29 @@
import { isString } from "lodash";
export const DEFAULT_STORAGE_KEY = "token";
export interface TokenStorageOptions {
key?: string;
}
export default class TokenStorage {
public key: string;
public token: string | null;
constructor({ key }: TokenStorageOptions = {}) {
this.key = isString(key) ? key : DEFAULT_STORAGE_KEY;
this.token = this.loadToken();
}
private loadToken() {
return localStorage.getItem(this.key);
}
private saveToken(token: string) {
return localStorage.setItem(this.key, token);
}
public setToken(newToken: string) {
this.token = newToken;
this.saveToken(newToken);
}
}