UNPKG

@graphql-hive/core

Version:
61 lines (60 loc) 2.3 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.createPersistedDocuments = createPersistedDocuments; const tslib_1 = require("tslib"); const tiny_lru_1 = tslib_1.__importDefault(require("tiny-lru")); const http_client_js_1 = require("./http-client.js"); function createPersistedDocuments(config) { var _a; const persistedDocumentsCache = (0, tiny_lru_1.default)((_a = config.cache) !== null && _a !== void 0 ? _a : 10000); let allowArbitraryDocuments; if (typeof config.allowArbitraryDocuments === 'boolean') { let value = config.allowArbitraryDocuments; allowArbitraryDocuments = () => value; } else if (typeof config.allowArbitraryDocuments === 'function') { allowArbitraryDocuments = config.allowArbitraryDocuments; } else { allowArbitraryDocuments = () => false; } /** if there is already a in-flight request for a document, we re-use it. */ const fetchCache = new Map(); /** Batch load a persisted documents */ function loadPersistedDocument(documentId) { const document = persistedDocumentsCache.get(documentId); if (document) { return document; } const cdnDocumentId = documentId.replaceAll('~', '/'); const url = config.cdn.endpoint + '/apps/' + cdnDocumentId; let promise = fetchCache.get(url); if (!promise) { promise = http_client_js_1.http .get(url, { headers: { 'X-Hive-CDN-Key': config.cdn.accessToken, }, logger: config.logger, isRequestOk: response => response.status === 200 || response.status === 404, }) .then(async (response) => { if (response.status !== 200) { return null; } const text = await response.text(); persistedDocumentsCache.set(documentId, text); return text; }) .finally(() => { fetchCache.delete(url); }); fetchCache.set(url, promise); } return promise; } return { allowArbitraryDocuments, resolve: loadPersistedDocument, }; }