graphql-yoga
Version: 
<div align="center"><img src="https://raw.githubusercontent.com/graphql-hive/graphql-yoga/refs/heads/main/website/public/cover.png" width="720" /></div>
62 lines (61 loc) • 2.13 kB
JavaScript
import { isSchema } from 'graphql';
import { handleMaybePromise } from '@whatwg-node/promise-helpers';
export const useSchema = (schemaDef) => {
    if (schemaDef == null) {
        return {};
    }
    if (isSchema(schemaDef)) {
        return {
            onPluginInit({ setSchema }) {
                setSchema(schemaDef);
            },
        };
    }
    if ('then' in schemaDef) {
        let schema;
        return {
            onRequestParse() {
                return {
                    onRequestParseDone() {
                        if (!schema) {
                            return handleMaybePromise(() => schemaDef, schemaDef => {
                                schema = schemaDef;
                            });
                        }
                    },
                };
            },
            onEnveloped({ setSchema }) {
                if (!schema) {
                    throw new Error(`You provide a promise of a schema but it hasn't been resolved yet. Make sure you use this plugin with GraphQL Yoga.`);
                }
                setSchema(schema);
            },
        };
    }
    const schemaByRequest = new WeakMap();
    return {
        onRequestParse({ request, serverContext }) {
            return {
                onRequestParseDone() {
                    return handleMaybePromise(() => schemaDef({
                        ...serverContext,
                        request,
                    }), schemaDef => {
                        schemaByRequest.set(request, schemaDef);
                    });
                },
            };
        },
        onEnveloped({ setSchema, context }) {
            if (context?.request == null) {
                throw new Error('Request object is not available in the context. Make sure you use this plugin with GraphQL Yoga.');
            }
            const schema = schemaByRequest.get(context.request);
            if (schema == null) {
                throw new Error(`No schema found for this request. Make sure you use this plugin with GraphQL Yoga.`);
            }
            setSchema(schema);
        },
    };
};