import { jsonToGraphQLQuery } from 'json-to-graphql-query';

export const requestTaylor = async (query: object, variables?: object) => {
  const body = JSON.stringify({
    query: jsonToGraphQLQuery(query),
    variables,
  });

  const response = await fetch(process.env.TAYLOR_API_ENDPOINT || '', {
    body,
    method: 'POST',
    headers: {
      Authorization: process.env.TAYLOR_API_TOKEN || '',
      'Content-type': 'application/json',
      schema: 'readable',
    },
  });

  const parsedResponse = await response.json();

  if (parsedResponse.errors) {
    throw parsedResponse.errors;
  }

  return parsedResponse;
};
