import { IntrospectionFragmentMatcher, NormalizedCacheObject } from "apollo-cache-inmemory"; import { IError, errors, defaultError, refreshSuggestion } from "@/utils/errors"; import { AUTH_ACCESS_TOKEN, AUTH_REFRESH_TOKEN } from "@/constants"; import { REFRESH_TOKEN } from "@/graphql/auth"; import { saveTokenData } from "@/utils/auth"; import { ApolloClient } from "apollo-client"; export const fragmentMatcher = new IntrospectionFragmentMatcher({ introspectionQueryResultData: { __schema: { types: [ { kind: "UNION", name: "SearchResult", possibleTypes: [{ name: "Event" }, { name: "Person" }, { name: "Group" }], }, { kind: "INTERFACE", name: "Actor", possibleTypes: [{ name: "Person" }, { name: "Group" }], }, ], }, }, }); export const computeErrorMessage = (message: any) => { const error: IError = errors.reduce((acc, errorLocal) => { if (RegExp(errorLocal.match).test(message)) { return errorLocal; } return acc; }, defaultError); if (error.value === null) return null; return error.suggestRefresh === false ? error.value : `${error.value}
${refreshSuggestion}`; }; export async function refreshAccessToken( apolloClient: ApolloClient ): Promise { // Remove invalid access token, so the next request is not authenticated localStorage.removeItem(AUTH_ACCESS_TOKEN); const refreshToken = localStorage.getItem(AUTH_REFRESH_TOKEN); console.log("Refreshing access token."); try { const res = await apolloClient.mutate({ mutation: REFRESH_TOKEN, variables: { refreshToken, }, }); saveTokenData(res.data.refreshToken); return true; } catch (err) { return false; } }