UNPKG

@graphiql/react

Version:

[Changelog](https://github.com/graphql/graphiql/blob/main/packages/graphiql-react/CHANGELOG.md) | [API Docs](https://graphiql-test.netlify.app/typedoc/modules/graphiql_react.html) | [NPM](https://www.npmjs.com/package/@graphiql/react)

110 lines (109 loc) 3.41 kB
import { fetcherReturnToPromise, isPromise, formatResult, formatError } from "@graphiql/toolkit"; import { getIntrospectionQuery, buildClientSchema } from "graphql"; import { tryParseJSONC } from "../utility/jsonc.js"; const createSchemaSlice = (initial) => (set, get) => ({ ...initial, fetchError: null, isIntrospecting: false, schema: null, /** * Derive validation errors from the schema */ validationErrors: [], schemaReference: null, requestCounter: 0, shouldIntrospect: true, actions: { setSchemaReference(schemaReference) { set({ schemaReference }); }, async introspect() { const { requestCounter, shouldIntrospect, onSchemaChange, headerEditor, fetcher, inputValueDeprecation, introspectionQueryName, schemaDescription } = get(); if (!shouldIntrospect) { return; } const counter = requestCounter + 1; set({ requestCounter: counter, isIntrospecting: true, fetchError: null }); try { let doIntrospection = function(query) { const fetch = fetcherReturnToPromise(fetcher({ query, operationName: introspectionQueryName }, fetcherOpts)); if (!isPromise(fetch)) { throw new TypeError("Fetcher did not return a Promise for introspection."); } return fetch; }; let headers; try { headers = tryParseJSONC(headerEditor == null ? void 0 : headerEditor.getValue()); } catch (error) { throw new Error(`Introspection failed. Request headers ${error instanceof Error ? error.message : error}`); } const fetcherOpts = headers ? { headers } : {}; const introspectionQuery = getIntrospectionQuery({ inputValueDeprecation, schemaDescription }); const normalizedQuery = introspectionQueryName === "IntrospectionQuery" ? introspectionQuery : introspectionQuery.replace("query IntrospectionQuery", `query ${introspectionQueryName}`); let result = await doIntrospection(normalizedQuery); if (typeof result !== "object" || !("data" in result)) { result = await doIntrospection(introspectionQuery.replace("subscriptionType { name }", "")); } set({ isIntrospecting: false }); let introspectionData; if (result.data && "__schema" in result.data) { introspectionData = result.data; } else { const responseString = typeof result === "string" ? result : formatResult(result); set({ fetchError: responseString }); } if (counter !== get().requestCounter || !introspectionData) { return; } const newSchema = buildClientSchema(introspectionData); set({ schema: newSchema }); onSchemaChange == null ? void 0 : onSchemaChange(newSchema); } catch (error) { if (counter !== get().requestCounter) { return; } if (error instanceof Error) { delete error.stack; } set({ isIntrospecting: false, fetchError: formatError(error) }); } } } }); export { createSchemaSlice }; //# sourceMappingURL=schema.js.map