UNPKG

@envelop/parser-cache

Version:
39 lines (38 loc) 1.51 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.useParserCache = void 0; const graphql_1 = require("graphql"); const lru_cache_1 = require("lru-cache"); const DEFAULT_MAX = 1000; const DEFAULT_TTL = 3_600_000; const useParserCache = (pluginOptions = {}) => { const documentCache = typeof pluginOptions.documentCache === 'undefined' ? new lru_cache_1.LRUCache({ max: DEFAULT_MAX, ttl: DEFAULT_TTL }) : pluginOptions.documentCache; const errorCache = typeof pluginOptions.errorCache === 'undefined' ? new lru_cache_1.LRUCache({ max: DEFAULT_MAX, ttl: DEFAULT_TTL }) : pluginOptions.errorCache; return { onParse({ params, setParsedDocument }) { const { source } = params; const key = source instanceof graphql_1.Source ? source.body : source; const cachedError = errorCache.get(key); if (cachedError !== undefined) { throw cachedError; } const cachedDocument = documentCache.get(key); if (cachedDocument !== undefined) { setParsedDocument(cachedDocument); } return ({ result }) => { if (result instanceof Error) { errorCache.set(key, result); } else if (result !== null) { documentCache.set(key, result); } }; }, }; }; exports.useParserCache = useParserCache;