GraphQL解析GraphQLObjectType

时间:2017-04-22 16:33:46

标签: javascript express graphql

我使用express-graphql以及以下查询:

invitations {
    sent 
    received
}

架构定义(简化)如下:

const InvitationType = new GraphQLObjectType({
    name: 'InvitationType',
    description: 'Friends invitations',
    fields: {
        sent: {
            type: new GraphQLList(GraphQLString),
            description: 'Invitations sent to friends.',
            resolve() {
             return ['sentA'];
            }
        },
        received: {
            type: new GraphQLList(GraphQLString),
            description: 'Invitations received from friends.',
            resolve() {
             return ['receivedA', 'receivedB'];
            }
        }
    }
});

// Root schema
const schema = new GraphQLSchema({
    query: new GraphQLObjectType({
      name: 'RootQueryType',
      fields: {
          invitations: {
              type: InvitationType // no resolve() method here.
          }
      }
    })
});

但是,永远不会为resolvesent字段调用received方法。上面的查询返回:

{data: {invitations: {sent: null, received: null}}}

有没有办法解决嵌套字段(sentreceived)而不在父(resolve())字段上定义invitations方法?

1 个答案:

答案 0 :(得分:1)

这对我有用!根据{{​​3}},如果resolve方法返回非标量,则执行将继续。所以下面的代码可以工作:

// Root schema
const schema = new GraphQLSchema({
    query: new GraphQLObjectType({
      name: 'RootQueryType',
      fields: {
        invitations: {
          type: InvitationType,
          resolve: () => ({}) // Resolve returns an object.
        }
      }
    })
});

希望这会有所帮助。干杯!