feat: align auth api with front convention (#370)

* feat: align auth api with front convention

* fix: email password auth

* fix: proper file naming

* Fix login

---------

Co-authored-by: Charles Bochet <charles@twenty.com>
This commit is contained in:
Jérémy M
2023-06-24 07:43:54 +02:00
committed by GitHub
parent c6708b2c1f
commit 31145c5518
23 changed files with 222 additions and 293 deletions

View File

@ -0,0 +1,57 @@
import { useEffect, useMemo, useRef } from 'react';
import { InMemoryCache, NormalizedCacheObject } from '@apollo/client';
import { useRecoilState } from 'recoil';
import { tokenPairState } from '@/auth/states/tokenPairState';
import { CommentThreadTarget } from '~/generated/graphql';
import { ApolloFactory } from '../services/apollo.factory';
export function useApolloFactory() {
const apolloRef = useRef<ApolloFactory<NormalizedCacheObject> | null>(null);
const [tokenPair, setTokenPair] = useRecoilState(tokenPairState);
const apolloClient = useMemo(() => {
apolloRef.current = new ApolloFactory({
uri: `${process.env.REACT_APP_API_URL}`,
cache: new InMemoryCache({
typePolicies: {
CommentThread: {
fields: {
commentThreadTargets: {
merge(
existing: CommentThreadTarget[] = [],
incoming: CommentThreadTarget[],
) {
return [...incoming];
},
},
},
},
},
}),
defaultOptions: {
query: {
fetchPolicy: 'cache-first',
},
},
onTokenPairChange(tokenPair) {
setTokenPair(tokenPair);
},
onUnauthenticatedError() {
setTokenPair(null);
},
});
return apolloRef.current.getClient();
}, [setTokenPair]);
useEffect(() => {
if (apolloRef.current) {
apolloRef.current.updateTokenPair(tokenPair);
}
}, [tokenPair]);
return apolloClient;
}

View File

@ -0,0 +1,44 @@
import { useMemo } from 'react';
import {
ApolloClient,
ApolloLink,
createHttpLink,
from,
InMemoryCache,
} from '@apollo/client';
import { mockedCompaniesData } from '~/testing/mock-data/companies';
import { mockedUsersData } from '~/testing/mock-data/users';
export default function useApolloMocked() {
const mockedClient = useMemo(() => {
const apiLink = createHttpLink({
uri: `${process.env.REACT_APP_API_URL}`,
});
const mockLink = new ApolloLink((operation, forward) => {
return forward(operation).map((response) => {
if (operation.operationName === 'GetCompanies') {
return { data: { companies: mockedCompaniesData } };
}
if (operation.operationName === 'GetCurrentUser') {
return { data: { users: [mockedUsersData[0]] } };
}
return response;
});
});
return new ApolloClient({
link: from([mockLink, apiLink]),
cache: new InMemoryCache(),
defaultOptions: {
query: {
fetchPolicy: 'cache-first',
},
},
});
}, []);
return mockedClient;
}

View File

@ -0,0 +1,8 @@
import { ApolloClient } from '@apollo/client';
import { AuthTokenPair } from '~/generated/graphql';
export interface ApolloManager<TCacheShape> {
getClient(): ApolloClient<TCacheShape>;
updateTokenPair(tokenPair: AuthTokenPair | null): void;
}

View File

@ -0,0 +1,172 @@
/* eslint-disable no-loop-func */
import {
ApolloClient,
ApolloClientOptions,
ApolloLink,
createHttpLink,
ServerError,
ServerParseError,
} from '@apollo/client';
import { GraphQLErrors } from '@apollo/client/errors';
import { setContext } from '@apollo/client/link/context';
import { onError } from '@apollo/client/link/error';
import { RetryLink } from '@apollo/client/link/retry';
import { Observable } from '@apollo/client/utilities';
import { renewToken } from '@/auth/services/AuthService';
import { AuthTokenPair } from '~/generated/graphql';
import { loggerLink } from '../../utils/apollo-logger';
import { assertNotNull } from '../../utils/assert';
import { promiseToObservable } from '../../utils/promise-to-observable';
import { ApolloManager } from '../interfaces/apolloManager.interface';
const logger = loggerLink(() => 'Twenty');
let isRefreshing = false;
let pendingRequests: (() => void)[] = [];
const resolvePendingRequests = () => {
pendingRequests.map((callback) => callback());
pendingRequests = [];
};
export interface Options<TCacheShape> extends ApolloClientOptions<TCacheShape> {
onError?: (err: GraphQLErrors | undefined) => void;
onNetworkError?: (err: Error | ServerParseError | ServerError) => void;
onTokenPairChange?: (tokenPair: AuthTokenPair) => void;
onUnauthenticatedError?: () => void;
}
export class ApolloFactory<TCacheShape> implements ApolloManager<TCacheShape> {
private client: ApolloClient<TCacheShape>;
private tokenPair: AuthTokenPair | null = null;
constructor(opts: Options<TCacheShape>) {
const {
uri,
onError: onErrorCb,
onNetworkError,
onTokenPairChange,
onUnauthenticatedError,
...options
} = opts;
const buildApolloLink = (): ApolloLink => {
const httpLink = createHttpLink({
uri,
});
const authLink = setContext(async (_, { headers }) => {
return {
headers: {
...headers,
authorization: this.tokenPair?.accessToken.token
? `Bearer ${this.tokenPair?.accessToken.token}`
: '',
},
};
});
const retryLink = new RetryLink({
delay: {
initial: 100,
},
attempts: {
max: 2,
retryIf: (error) => !!error,
},
});
const errorLink = onError(
({ graphQLErrors, networkError, forward, operation }) => {
if (graphQLErrors) {
onErrorCb?.(graphQLErrors);
for (const graphQLError of graphQLErrors) {
switch (graphQLError?.extensions?.code) {
case 'UNAUTHENTICATED': {
// error code is set to UNAUTHENTICATED
// when AuthenticationError thrown in resolver
let forward$: Observable<boolean>;
if (!isRefreshing) {
isRefreshing = true;
forward$ = promiseToObservable(
renewToken(uri, this.tokenPair)
.then((tokens) => {
onTokenPairChange?.(tokens);
resolvePendingRequests();
return true;
})
.catch(() => {
pendingRequests = [];
onUnauthenticatedError?.();
return false;
})
.finally(() => {
isRefreshing = false;
}),
).filter((value) => Boolean(value));
} else {
// Will only emit once the Promise is resolved
forward$ = promiseToObservable(
new Promise<boolean>((resolve) => {
pendingRequests.push(() => resolve(true));
}),
);
}
return forward$.flatMap(() => forward(operation));
}
default:
if (process.env.NODE_ENV === 'development') {
console.warn(
`[GraphQL error]: Message: ${
graphQLError.message
}, Location: ${
graphQLError.locations
? JSON.stringify(graphQLError.locations)
: graphQLError.locations
}, Path: ${graphQLError.path}`,
);
}
}
}
}
if (networkError) {
if (process.env.NODE_ENV === 'development') {
console.warn(`[Network error]: ${networkError}`);
}
onNetworkError?.(networkError);
}
},
);
return ApolloLink.from(
[
errorLink,
authLink,
// Only show logger in dev mode
process.env.NODE_ENV !== 'production' ? logger : null,
retryLink,
httpLink,
].filter(assertNotNull),
);
};
this.client = new ApolloClient({
...options,
link: buildApolloLink(),
});
}
updateTokenPair(tokenPair: AuthTokenPair | null) {
this.tokenPair = tokenPair;
}
getClient() {
return this.client;
}
}