Search code examples
graphqlgraphiql

GraphQL add introspection from a variable


I want to add introspection from a variable to my app.

I have this kind of introspection:

{"data":{"__schema":{"queryType":{"name":"PageContentQuery"}....  

(that im getting from rest request)

I want this variable to be the schema provider, is it possible?

The full variable is here: https://stackblitz.com/edit/ts-graphql-demo-ypgi18?file=index.tsx

const fetcher = (params: any) => {
  console.log(params);
  return graphql(schema, params.query, params.variables);
}

const defaultQuery = `{
 page{id,contents}
}`;

render(
  <GraphiQL fetcher={fetcher} schema={schema} defaultQuery={defaultQuery}/>,
  document.getElementById('root'),
);

thanks


Solution

  • Given the results of an introspection query, you can build a schema using buildClientSchema:

    import { buildClientSchema } from 'graphql'
    
    const schema = buildClientSchema(introspectionResult)
    

    You can then pass that schema as prop to the GraphiQL component:

    <GraphiQL fetcher={fetcher} schema={schema} />
    

    Of course, that's generally not necessary -- if the schema is not passed in, then GraphiQL will just make an introspection query for you using the fetcher you provide.