UNPKG

@graphql-mesh/serve-runtime

Version:
40 lines (39 loc) 1.62 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.useChangingSchema = useChangingSchema; const utils_1 = require("@graphql-mesh/utils"); function useChangingSchema(getSchema, schemaChanged) { let currentSchema; const schemaByRequest = new WeakMap(); return { onPluginInit({ setSchema }) { schemaChanged(schema => { if (currentSchema !== schema) { setSchema(schema); currentSchema = schema; } }); }, onRequestParse({ request }) { return { onRequestParseDone() { if (!currentSchema) { // only if the schema is not already set do we want to get it return (0, utils_1.mapMaybePromise)(getSchema(), schema => { schemaByRequest.set(request, schema); }); // TODO: PromiseLike in Mesh MaybePromise is not assignable to type Yoga's PromiseOrValue } }, }; }, onEnveloped({ context, setSchema }) { const schema = context?.request && schemaByRequest.get(context.request); if (schema && currentSchema !== schema) { // the schema will be available in the request only if schemaChanged was never invoked // also avoid setting the schema multiple times by checking whether it was already set setSchema(schema); currentSchema = schema; } }, }; }