使用graphiql检查远程graphql端点

Jos*_*elo 6 graphql graphql-js

有一个graphql端点,我不拥有,但它提供了一个公共端点.我希望用graphiql来反省它.我对graphql完全不熟悉,所以我甚至都不知道这种事情是否可行.

我有本地运行的graphiql示例,我正在修改server.js以尝试使其工作.在其他SO线程中探索已经让我这么远......

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);
Run Code Online (Sandbox Code Playgroud)

此代码在GraphQLSchema构造函数中爆炸,尝试从该内省查询中创建一个模式.显然,这不是一个正确的方法?

小智 4

您想要根据内省结果构建模式是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);
Run Code Online (Sandbox Code Playgroud)

您可以通过其他两种方式构建架构:直接buildASTSchema实例化GraphQLSchema,这就是您正在尝试的方法。GraphQLSchema构造函数接受一个GraphQLSchemaConfig类型为的对象:

type GraphQLSchemaConfig = {
  query: GraphQLObjectType;
  mutation?: ?GraphQLObjectType;
  subscription?: ?GraphQLObjectType;
  types?: ?Array<GraphQLNamedType>;
  directives?: ?Array<GraphQLDirective>;
};
Run Code Online (Sandbox Code Playgroud)

buildClientSchema这两个实用程序模块提供了更简单的方法,分别通过使用或从内省查询结果或解析的 IDL 类型定义构建模式buildASTSchema。请参阅graphql-js/src/utilities目录中的模块以获取更多信息。