"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.gqlFetchAll = exports.gqlFetch = void 0;
const graphql_request_1 = require("graphql-request");
const gqlFetch = ({ endpoint, query, variables = {}, headers = {}, }) => __awaiter(void 0, void 0, void 0, function* () {
    const client = new graphql_request_1.GraphQLClient(endpoint, { headers });
    return client.request(query, variables);
});
exports.gqlFetch = gqlFetch;
const gqlFetchAll = ({ query, endpoint, variables = {}, dataToSearch, first = 1000, lastId = '', prevResults, }) => __awaiter(void 0, void 0, void 0, function* () {
    const results = yield (0, exports.gqlFetch)({
        endpoint,
        query,
        variables: Object.assign(Object.assign({}, variables), { first: first, lastId }),
    });
    if (results[dataToSearch].length === first) {
        let newPrevResults = results;
        if (prevResults) {
            newPrevResults = Object.assign(Object.assign(Object.assign({}, prevResults), results), { [dataToSearch]: [...prevResults[dataToSearch], ...results[dataToSearch]] });
        }
        return (0, exports.gqlFetchAll)({
            query,
            endpoint,
            variables,
            dataToSearch,
            first: first,
            lastId: results[dataToSearch][results[dataToSearch].length - 1].id,
            prevResults: newPrevResults,
        });
    }
    if (prevResults) {
        return Object.assign(Object.assign(Object.assign({}, prevResults), results), { [dataToSearch]: [...prevResults[dataToSearch], ...results[dataToSearch]] });
    }
    else {
        return results;
    }
});
exports.gqlFetchAll = gqlFetchAll;
//# sourceMappingURL=the-graph.helper.js.map