fetch.ts

import fetch from 'node-fetch';
import AbortController from 'abort-controller';
import { url } from '../../config';
import { apiPrefix } from '../constants/app';

export async function fetchFromGraphQL({ query = '', variables = {}, referer = null }) {
  // Setting up request timeout
  const controller = new AbortController();
  const timeout = setTimeout(() => {
    controller.abort();
  }, 5000);

  const fetchOptions = {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      Accept: 'application/json',
      Referer: referer
    },
    body: JSON.stringify({
      query,
      variables
    }),
    signal: controller.signal
  };

  try {
    const response = await fetch(`${url.API_BACKEND}/private/graphql`, fetchOptions);
    const { data } = await response.json();
    return data;
  } catch (error) {
    console.error('Fetch rejected: ', error);
  } finally {
    clearTimeout(timeout);
  }

  return null;
}

export async function fetchFromApi({ url }) {
  const response = await fetch(url);
  const { data } = await response.json();
  return data;
}

// This isnt working. Reason unknown.
// Could be failing while using with the homepage rewrite due to api execution order
/*
export async function fetchFromCocoApi({ path }) {
  const apiEndpointUrl = `${url.API_BACKEND}${apiPrefix}${path}`;

  const fetchOptions = {
    method: 'GET',
    headers: {
      'Content-Type': 'application/json',
      Accept: 'application/json',
      Referer: 'https://coco.is/'
    }
  };
  try {
    const response = await fetch(apiEndpointUrl, fetchOptions);
    const { data } = await response.json();
    return data;
  } catch (error) {
    console.error(error);
  }
  return null;
}
*/