From f111685c5886f3e77edfd3621c98d8ac1b9bcce4 Mon Sep 17 00:00:00 2001 From: Armand Philippot Date: Fri, 24 Nov 2023 20:00:08 +0100 Subject: refactor(services, types): reorganize GraphQL fetchers and data types The Typescript mapped types was useful for autocompletion in fetchers but their are harder to maintain. I think it's better to keep each query close to its fetcher to have a better understanding of the fetched data. So I: * colocate queries with their own fetcher * colocate mutations with their own mutator * remove Typescript mapped types for queries and mutations * move data convertors inside graphql services * rename most of data types and fetchers --- src/services/graphql/api.ts | 83 --------------------------------------------- 1 file changed, 83 deletions(-) delete mode 100644 src/services/graphql/api.ts (limited to 'src/services/graphql/api.ts') diff --git a/src/services/graphql/api.ts b/src/services/graphql/api.ts deleted file mode 100644 index 003f92d..0000000 --- a/src/services/graphql/api.ts +++ /dev/null @@ -1,83 +0,0 @@ -import type { - Mutations, - MutationsInputMap, - MutationsResponseMap, - Queries, - QueriesInputMap, - QueriesResponseMap, -} from '../../types'; -import { CONFIG } from '../../utils/config'; - -/** - * Retrieve the API url from settings. - * - * @returns {string} The API url. - */ -export const getAPIUrl = (): string => { - const { url } = CONFIG.api; - - if (!url) { - throw new Error('API url is not defined.'); - } - - return url; -}; - -export type ResponseMap = K extends Mutations - ? MutationsResponseMap - : QueriesResponseMap; - -export type InputMap = T extends Mutations - ? MutationsInputMap - : QueriesInputMap; - -type FetchAPIVariables = T extends Queries - ? QueriesInputMap[T] - : T extends Mutations - ? MutationsInputMap[T] - : never; - -type FetchAPIProps> = { - query: Q; - variables?: V; -}; - -type FetchAPIResponse = K extends Queries - ? QueriesResponseMap[K] - : K extends Mutations - ? MutationsResponseMap[K] - : never; - -export const fetchAPI = async ({ - query, - variables, -}: FetchAPIProps): Promise> => { - const response = await fetch(getAPIUrl(), { - method: 'POST', - headers: { - 'content-type': 'application/json;charset=UTF-8', - }, - body: JSON.stringify({ - query, - variables, - }), - }); - - type JSONResponse = { - data?: FetchAPIResponse; - errors?: { message: string }[]; - }; - - const { data, errors }: JSONResponse = await response.json(); - - if (response.ok) { - if (!data) return Promise.reject(new Error(`No data found"`)); - - return data; - } - console.error('Failed to fetch API'); - const error = new Error( - errors?.map((e) => e.message).join('\n') ?? 'unknown' - ); - return Promise.reject(error); -}; -- cgit v1.2.3