add two libs: graphql and tokenstorage
This commit is contained in:
parent
4c64bc70a5
commit
0ea3eb8b07
|
@ -0,0 +1,2 @@
|
|||
export const API_URI =
|
||||
process.env.REACT_APP_API_URI ?? "http://localhost:8080/graphql";
|
|
@ -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;
|
|
@ -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;
|
|
@ -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);
|
||||
}
|
||||
}
|
Reference in New Issue