【问题标题】:Inspecting a remote graphql endpoint with graphiql使用 graphiql 检查远程 graphql 端点
【发布时间】:2017-03-19 23:55:51
【问题描述】:

有一个我不拥有但提供公共端点的 graphql 端点。我希望使用 graphiql 对其进行反省。我对graphql完全陌生,所以我什至不知道这种事情是否可能。

我有 graphiql example 在本地运行,我正在修改 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);

这段代码在 GraphQLSchema 构造函数中爆炸,试图从自省查询中创建一个模式。显然这不是正确的方法?

【问题讨论】:

    标签: graphql graphql-js


    【解决方案1】:

    你想从内省结果中构建模式是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);
    

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

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

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

    【讨论】:

    【解决方案2】:

    我正在尝试使用 PHP GraphQL 库。我在围绕 CORS(跨源安全问题)进行上述试验时遇到了很多问题。

    然后我发现 GraphIQL 可以作为 Chrome 应用程序使用。这解决了我的需求,因此请注意此处以防遇到此问题的其他人有用。您无需进行任何编码即可使 GraphIQL 与远程端点一起工作。

    【讨论】:

      猜你喜欢
      • 2016-02-04
      • 2018-05-25
      • 2020-11-12
      • 2020-10-01
      • 2020-08-07
      • 2017-09-01
      • 2021-07-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多