* merge squashed
- A couple of CJS modules into ESM (config mostly)
- Vite complains about node.js modules: fixed `useIsMatchingLocation.ts`
> or use rollupOptions in vite.config.ts
> ref: f0e4f59d97/vite.config.js (L6)
- Adjust Storybook to work with Vite: use @storybook/test
- Use SWC for jest tranformations
- Remove unused deps:
- ts-jest: replaced with @swc/jest, typecheck by `tsc`
- babel plugins
- @svgr/plugin-jsx: not used
- @testing-library/user-event: handled by @storybook/test
- @typescript-eslint/utils: was not plugged in
- tsup, esbuild-plugin-svgr: will look into that later
- Install Vite required deps, and remove craco/webpack deps
- Adjust SVG to work with Vite as components
- Fixed `Step.tsx`: I dont know if one should be swaped for the other,
but there should be no slash
- Initial formating and linting:
- removed empty object params
- sorting imports, etc..
* prettier: fix pattern
* coverage: sb coverage report isnt working
* Add missing pieces
* `yarn lint --fix`
* fix: scripts permissions
* tsc: cut errors in half
* fix: remove `react-app-env.d.ts`
* tsc: all fixed, except `react-data-grid` types issue
* eslint: ignore env-config.js
* eslint: Align ci with config
* msw: bypass testing warnings
ref: https://stackoverflow.com/questions/68024935/msw-logging-warnings-for-unhandled-supertest-requests
* rebase: and fix things
* Adjust to current `graphql-codegen` no ESM support
* Remove vite plugin and use built-in methods
* rebase: and some fixes
* quick fix + `corepack use yarn@1.22.19`
* Fix build errors
---------
Co-authored-by: Charles Bochet <charles@twenty.com>
160 lines
4.5 KiB
TypeScript
160 lines
4.5 KiB
TypeScript
import {
|
|
ApolloClient,
|
|
ApolloClientOptions,
|
|
ApolloLink,
|
|
fromPromise,
|
|
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 { createUploadLink } from 'apollo-upload-client';
|
|
|
|
import { renewToken } from '@/auth/services/AuthService';
|
|
import { AuthTokenPair } from '~/generated/graphql';
|
|
import { assertNotNull } from '~/utils/assert';
|
|
import { logDebug } from '~/utils/logDebug';
|
|
|
|
import { ApolloManager } from '../types/apolloManager.interface';
|
|
import { loggerLink } from '../utils';
|
|
|
|
const logger = loggerLink(() => 'Twenty');
|
|
|
|
export interface Options<TCacheShape> extends ApolloClientOptions<TCacheShape> {
|
|
onError?: (err: GraphQLErrors | undefined) => void;
|
|
onNetworkError?: (err: Error | ServerParseError | ServerError) => void;
|
|
onTokenPairChange?: (tokenPair: AuthTokenPair) => void;
|
|
onUnauthenticatedError?: () => void;
|
|
initialTokenPair: AuthTokenPair | null;
|
|
extraLinks?: ApolloLink[];
|
|
isDebugMode?: boolean;
|
|
}
|
|
|
|
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,
|
|
initialTokenPair,
|
|
extraLinks,
|
|
isDebugMode,
|
|
...options
|
|
} = opts;
|
|
|
|
this.tokenPair = initialTokenPair;
|
|
|
|
const buildApolloLink = (): ApolloLink => {
|
|
const httpLink = createUploadLink({
|
|
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: 3000,
|
|
},
|
|
attempts: {
|
|
max: 2,
|
|
retryIf: (error) => !!error,
|
|
},
|
|
});
|
|
const errorLink = onError(
|
|
({ graphQLErrors, networkError, forward, operation }) => {
|
|
if (graphQLErrors) {
|
|
onErrorCb?.(graphQLErrors);
|
|
|
|
for (const graphQLError of graphQLErrors) {
|
|
if (graphQLError.message === 'Unauthorized') {
|
|
return fromPromise(
|
|
renewToken(uri, this.tokenPair)
|
|
.then((tokens) => {
|
|
onTokenPairChange?.(tokens);
|
|
})
|
|
.catch(() => {
|
|
onUnauthenticatedError?.();
|
|
}),
|
|
).flatMap(() => forward(operation));
|
|
}
|
|
|
|
switch (graphQLError?.extensions?.code) {
|
|
case 'UNAUTHENTICATED': {
|
|
return fromPromise(
|
|
renewToken(uri, this.tokenPair)
|
|
.then((tokens) => {
|
|
onTokenPairChange?.(tokens);
|
|
})
|
|
.catch(() => {
|
|
onUnauthenticatedError?.();
|
|
}),
|
|
).flatMap(() => forward(operation));
|
|
}
|
|
default:
|
|
if (isDebugMode) {
|
|
logDebug(
|
|
`[GraphQL error]: Message: ${
|
|
graphQLError.message
|
|
}, Location: ${
|
|
graphQLError.locations
|
|
? JSON.stringify(graphQLError.locations)
|
|
: graphQLError.locations
|
|
}, Path: ${graphQLError.path}`,
|
|
);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
if (networkError) {
|
|
if (isDebugMode) {
|
|
logDebug(`[Network error]: ${networkError}`);
|
|
}
|
|
onNetworkError?.(networkError);
|
|
}
|
|
},
|
|
);
|
|
|
|
return ApolloLink.from(
|
|
[
|
|
errorLink,
|
|
authLink,
|
|
...(extraLinks || []),
|
|
isDebugMode ? logger : null,
|
|
retryLink,
|
|
httpLink,
|
|
].filter(assertNotNull),
|
|
);
|
|
};
|
|
|
|
this.client = new ApolloClient({
|
|
...options,
|
|
link: buildApolloLink(),
|
|
});
|
|
}
|
|
|
|
updateTokenPair(tokenPair: AuthTokenPair | null) {
|
|
this.tokenPair = tokenPair;
|
|
}
|
|
|
|
getClient() {
|
|
return this.client;
|
|
}
|
|
}
|