7

There is a graphql endpoint which I don't own but which provides a public endpoint. I'm hoping to introspect it using graphiql. I'm totally new to graphql, so I don't even know if this sort of thing is possible.

I have the graphiql example running locally and am modifying server.js to try to make it work. Poking around at other SO threads has gotten me this far...

var introspectionQuery = require('graphql/utilities').introspectionQuery;
var request            = require('sync-request');

var url = 'http://endpoint.com/graphql';
var response = request('POST', url, { qs: { query: introspectionQuery } } );
var schema = JSON.parse(response.body.toString('utf-8'));

// herein lies the rub
schema = new GraphQLSchema(schema.data.__schema);

var app = express();
app.use(express.static(__dirname));
app.use('/graphql', graphqlHTTP(() => ({
  schema: schema,
})));
app.listen(8080);

This code blows up in the GraphQLSchema constructor, trying to make a schema out of that introspection query. Clearly that's not quite the right approach?

2 Answers 2

4

What you want to build schema out of the introspection result is buildClientSchema:

var buildClientSchema  = require('graphql/utilities').buildClientSchema;
var introspectionQuery = require('graphql/utilities').introspectionQuery;
var request            = require('sync-request');

var response = request('POST', url, { qs: { query: introspectionQuery } });
// Assuming we're waiting for the above request to finish (await maybe)
var introspectionResult = JSON.parse(response.body.toString('utf-8'));
var schema = buildClientSchema(introspectionResult);

You could build the schema in two other ways: buildASTSchema and instantiating GraphQLSchema directly, which is what you're trying out. GraphQLSchema constructor takes in an object with GraphQLSchemaConfig type:

type GraphQLSchemaConfig = {
  query: GraphQLObjectType;
  mutation?: ?GraphQLObjectType;
  subscription?: ?GraphQLObjectType;
  types?: ?Array<GraphQLNamedType>;
  directives?: ?Array<GraphQLDirective>;
};

And those two utility modules provide easier ways to build the schema from either from introspection query result or parsed IDL type definitions, respectively by using buildClientSchema or buildASTSchema. Refer to those modules in graphql-js/src/utilities directory for more information please.

5
0

I was trying this with a PHP GraphQL library. I hit lots of issues experimenting with the above around CORS (cross origin security stuff).

Then I discovered GraphIQL is available as a Chrome app. That resolved my need, so noting here in case useful to anyone else who comes across this issue. You don't need to do any coding to get GraphIQL working with a remote endpoint.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.