aboutsummaryrefslogtreecommitdiffstats
path: root/src/services/graphql/api.ts
blob: 33cc89a715a8b08848f53bb9344676b97496e009 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import { RequestType, VariablesType } from '@ts/types/app';
import { GraphQLClient } from 'graphql-request';

export const getGraphQLClient = (): GraphQLClient => {
  const apiUrl: string = process.env.NEXT_PUBLIC_GRAPHQL_API || '';

  if (!apiUrl) throw new Error('API URL not defined.');

  return new GraphQLClient(apiUrl);
};

export const fetchApi = async <T extends RequestType>(
  query: string,
  variables: VariablesType<T>
): Promise<T> => {
  const client = getGraphQLClient();

  try {
    return await client.request(query, variables);
  } catch (error) {
    console.error(error, undefined, 2);
    process.exit(1);
  }
};