"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.getGqlFetch = void 0;
// @ts-check
const defaults = {
  getToken: () => null
};
/**
 * @param {{
 *   apiUrl: string
 *   getToken: () => string
 *   handleNotAuthorized: () => any
 *   handleNoAuthentication: () => any
 * }} options
 * @returns {(query: string, variables?: any) => Promise}
 */

const getGqlFetch = options => (query, variables = null) => {
  const opts = Object.assign({}, defaults, options);
  const token = opts.getToken();
  const encodedQuery = encodeURIComponent(query.trim());
  const tokenQuery = token ? "&token=".concat(token) : '';
  return fetch("".concat(opts.apiUrl, "/graphql?query=").concat(encodedQuery).concat(tokenQuery), {
    method: 'post',
    body: variables ? JSON.stringify({
      variables
    }) : null,
    headers: variables ? {
      'content-type': 'application/json'
    } : {}
  }).then(response => response.json()).then(parsed => {
    if (parsed.errors) {
      parsed.errors.forEach(error => {
        if (error.message === 'NO_AUTHENTICATION') {
          opts.handleNoAuthentication();
        }

        if (error.message === 'NOT_AUTHORIZED') {
          opts.handleNotAuthorized();
        }
      });
      throw parsed.errors;
    }

    return parsed;
  });
};

exports.getGqlFetch = getGqlFetch;