【问题标题】:Modify GraphQLObjectType fields at runtime在运行时修改 GraphQLObjectType 字段
【发布时间】:2017-07-25 01:48:08
【问题描述】:

假设我有以下代码作为 graphql 架构。一个userType,包括idname供用户使用,有两种查询:allUsers: [userType]user(id: Int!): userType

let db = [{
  id: 1,
  name: 'Amir'
}, {
  id: 2,
  name: 'John'
}];

const userType = new GraphQLObjectType({
  name: 'User',
  fields: {
    id: { type: GraphQLInt },
    name: { type: GraphQLString }
  }
});


const queryType = new GraphQLObjectType({
  name: 'Query',
  fields: {
    allUsers: {
      type: new GraphQLList(userType),
      resolve: () => db
    },
    user: {
      type: userType,
      args: {
        id: { type: new GraphQLNonNull(GraphQLInt) }
      },
      resolve: (_, { id }) => db.find(user => user.id == id);
    }
  }
})

let schema = new GraphQLSchema({ query: queryType });

我需要在启动时修改这个结构。我的意思是在实际执行最后一行之前。

为了添加更多类型的查询,在完成所有修改后,我将模式创建 (new GraphQLSchema(...)) 推迟到最后。所以我可以向查询本身添加更多字段,或者修改现有字段。

但是我怎样才能修改已经定义的类型基本上,我需要在userType中添加其他字段,比如permissions,它本身就是一个GraphQLObjectType,并且有自己的resolve函数。

类似这样的:

let queryFields = {};

const userType = new GraphQLObjectType({
  name: 'User',
  fields: {
    id: { type: GraphQLInt },
    name: { type: GraphQLString }
  }
});
queryFields['allUsers'] = {
  type: new GraphQLList(userType),
  // ...
}
queryFields['user'] = {
  type: userType,
  //...
}

/* HERE <---------------------------------------- */
userType.fields.permission = {
  type: GraphQLString,
  resolve: user => getPermissionsFor(user);
}


const queryType = new GraphQLObjectType({
  name: 'Query',
  fields: queryFields
})

var schema = new GraphQLSchema({ query: queryType });

谢谢!

【问题讨论】:

标签: javascript graphql graphql-js


【解决方案1】:

我最后所做的是在我的应用程序的逻辑和 GraphQL 之间添加另一层。所以我创建了另一个库来保存有关模式和类型的信息,它有一个 API 来修改模式中的现有类型。完成所有修改后,我们可以从库中提取 GraphQL 模式。

这就是整个想法。关于实现细节,我在这里写了一个帖子:Distributed Schema Creation in GraphQL

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多