From 9d9ba6540b6dfbc8d359d7f539873bef6e6bd7a3 Mon Sep 17 00:00:00 2001 From: vchikalkin Date: Thu, 2 Oct 2025 11:52:14 +0300 Subject: [PATCH] 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. --- packages/graphql/apollo/client.ts | 15 +++++++-------- packages/graphql/apollo/link.ts | 16 ++++++++++++++++ 2 files changed, 23 insertions(+), 8 deletions(-) create mode 100644 packages/graphql/apollo/link.ts diff --git a/packages/graphql/apollo/client.ts b/packages/graphql/apollo/client.ts index 7ee265f..dcbf72a 100644 --- a/packages/graphql/apollo/client.ts +++ b/packages/graphql/apollo/client.ts @@ -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, + }), }); } diff --git a/packages/graphql/apollo/link.ts b/packages/graphql/apollo/link.ts new file mode 100644 index 0000000..80b5607 --- /dev/null +++ b/packages/graphql/apollo/link.ts @@ -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]); +}