/ src / lib / graphql / dripsQL.ts
dripsQL.ts
 1  import uniqBy from 'lodash/uniqBy';
 2  import { parse } from 'graphql';
 3  import { GraphQLClient, type RequestDocument, type Variables } from 'graphql-request';
 4  import { addTypenameToDocument } from '@apollo/client/utilities';
 5  import { PUBLIC_GQL_URL, PUBLIC_INTERNAL_GQL_URL } from '$env/static/public';
 6  import { browser } from '$app/environment';
 7  
 8  export default async function query<TResponse, TVariables extends Variables = Variables>(
 9    query: RequestDocument,
10    variables?: TVariables,
11    customFetch: typeof fetch = fetch,
12  ): Promise<TResponse> {
13    const url = browser ? PUBLIC_GQL_URL : PUBLIC_INTERNAL_GQL_URL;
14    const client = new GraphQLClient(url, {
15      fetch: customFetch,
16    });
17  
18    const parsedQuery = typeof query === 'string' ? parse(query) : query;
19  
20    const queryWithTypenames = addTypenameToDocument(parsedQuery);
21  
22    return await client.request<TResponse>(
23      { ...queryWithTypenames, definitions: uniqBy(queryWithTypenames.definitions, 'name.value') },
24      variables,
25    );
26  }