UNPKG

genql-upload

Version:
50 lines (49 loc) 1.89 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.createFetcher = void 0; const form_data_1 = __importDefault(require("form-data")); const isomorphic_fetch_1 = __importDefault(require("isomorphic-fetch")); const extractFiles_1 = require("./extractFiles"); function createFetcher(opts) { const url = opts.url; return async (operation) => { if (Array.isArray(operation)) { throw new Error("Batch uploads are not supported"); } const { clone, files } = (0, extractFiles_1.extractFiles)(operation); const formData = new form_data_1.default(); // 1. First document is graphql query with variables formData.append("operations", JSON.stringify(clone)); // 2. Second document maps files to variable locations const map = {}; let i = 0; files.forEach((paths) => { map[i++] = paths; }); formData.append("map", JSON.stringify(map)); // 3. all files not (same index as in map) let j = 0; for (const [file] of files) { formData.append(`${j++}`, file.data, file.name); } // normal fetch let headersObject = typeof opts.headers == "function" ? await opts.headers() : opts.headers; headersObject = headersObject || {}; const res = await (0, isomorphic_fetch_1.default)(url, { method: "POST", headers: { ...headersObject, }, body: formData, }); if (!res.ok) { throw new Error(`${res.statusText}: ${await res.text()}`); } const json = (await res.json()); return json; }; } exports.createFetcher = createFetcher;