嵌套的GraphQL查询是否可能具有特定的id值?

时间:2017-08-09 16:23:01

标签: graphql

我已经成功构建了一个允许嵌套查询的GraphQL API。使用国家和通用的通用示例状态,我可以执行这样的查询:

    query{
      country(id:"Q291bnRyeTo0Nw==") {
        states {
          edges {
            node {
              id,
              name,
              area,
              population
            }
          }
        }
       }
     }

我发现我似乎无法做到的是:

query{
      country(id:"Q291bnRyeTo0Nw==") {
        state(id:"U3RhdGU6MzM=") {
          edges {
            node {
              id,
              name,
              area,
              population
            }
          }
        }
      }
    }

可以通过GraphQL在一个查询中指定特定的父级和特定子级吗?

罗伯特

更新:为了Daniel的好处,这是我当前的GraphQL查询代码:

from .models import Country as CountryModel
from .models import State as StateModel

class Query(graphene.AbstractType):

    country = graphene.Field(Country, id=graphene.String())
    countries = graphene.List(Country)

    state = graphene.Field(State, id=graphene.String())
    states = graphene.List(State)

    def resolve_country(self, args, context, info):
        id = args.get('id')

        if id is not None:
            return CountryModel.objects.get(id=Schema.decode(id))
    
        return None

    def resolve_countries(self, args, context, info):
        return CountryModel.objects.all()

    def resolve_state(self, args, context, info):
        id = args.get('id')

        if id is not None:
            return StateModel.objects.get(id=Schema.decode(id))
    
        return None

    def resolve_states(self, args, context, info):
        return StateModel.objects.all()

1 个答案:

答案 0 :(得分:4)

您需要为根查询中的country字段和国家/地区类型上的state字段定义解析程序。以下是您可以复制并粘贴到Launchpad并查看其实际效果的示例。

Graphene之类的设置会有所不同,但想法是一样的:country查询返回的对象可供state下每个字段的解析器使用类型。您使用传递给id字段的state参数来过滤该对象上的数据(在此示例中,返回的对象具有states属性)并返回适当的状态。

import { makeExecutableSchema } from 'graphql-tools';

const countries = [
  {
    id: 1,
    name: 'bar',
    states: [
      {
        name: 'foo',
        id: 20
      }
    ]
  },
  { id: 2 },
];

const typeDefs = `
  type Query {
    country(id: Int!): Country
  }
  type Country {
    id: Int
    state(id: Int!): State
  }
  type State {
   id: Int
   name: String
  }
`

const resolvers = {
  Query: {
    country: (obj, args, context) => {
      return countries.find(country => country.id === args.id)
    },
  },
  Country: {
    state: (obj, args, context) => {
      return obj.states.find(state => state.id === args.id)
    },
  }
}

export const schema = makeExecutableSchema({
  typeDefs,
  resolvers,
})

修改:假设CountryModel.objects.get(id=Schema.decode(id))返回的对象包含一个状态列表的states属性,您应该可以执行以下操作:

class Country(graphene.ObjectType):
  state = graphene.Field(State,
                          id=graphene.String()
                          )
  # other fields
  def resolve_state(self, args, context, info):
    id = args.get('id')
    if id is not None:
        return list(filter(lambda x: x.id == id, self.states)
    return None
相关问题