Refactor Apollo Client setup to improve modularity and maintainability

- Introduced a new `createLink` function to encapsulate the link creation logic for Apollo Client.
- Updated `createApolloClient` to utilize the new `createLink` function, enhancing code organization.
- Simplified the handling of authorization headers by moving it to the link configuration.
This commit is contained in:
vchikalkin 2025-10-02 11:52:14 +03:00
parent 54f69f7c36
commit 9d9ba6540b
2 changed files with 23 additions and 8 deletions

View File

@ -1,18 +1,17 @@
import { env as environment } from '../config/env';
import { getToken } from '../config/token';
import { createLink } from './link';
import { ApolloClient, InMemoryCache } from '@apollo/client/core';
type Parameters_ = { token: null | string | undefined };
type Parameters = { token: null | string | undefined };
export function createApolloClient(parameters?: Parameters_) {
export function createApolloClient(parameters?: Parameters) {
return new ApolloClient({
cache: new InMemoryCache(),
headers: parameters?.token
? {
Authorization: `Bearer ${parameters.token}`,
}
: undefined,
uri: environment.URL_GRAPHQL,
link: createLink({
token: parameters?.token,
uri: environment.URL_GRAPHQL,
}),
});
}

View File

@ -0,0 +1,16 @@
import { ApolloLink, from, HttpLink } from '@apollo/client';
type Parameters = { token: null | string | undefined; uri: string };
export function createLink({ token, uri }: Parameters) {
const cacheLink = new ApolloLink((operation, forward) => {
return forward(operation);
});
const httpLink = new HttpLink({
headers: token ? { Authorization: `Bearer ${token}` } : undefined,
uri,
});
return from([cacheLink, httpLink]);
}