我正在使用django graphene构建graphql服务器,它使用RESTfull API来获取数据,遵循以下模式:
class DeviceType(graphene.ObjectType):
id = graphene.ID()
reference = graphene.String()
serial = graphene.Float()
class InstallationType(graphene.ObjectType):
id = graphene.ID()
company = graphene.Int()
device = graphene.ID()
class AllDataType(graphene.ObjectType):
device = graphene.Field(DeviceType)
installation = graphene.Field(InstallationType)
class Query(graphene.ObjectType):
installation = graphene.Field(
InstallationType,
device_id=graphene.Int(required=True)
)
all = graphene.Field(
AllDataType,
serial=graphene.Float(required=True)
)
def resolve_installation(self, info, device_id):
response = api_call('installations/?device=%s' % device_id)['results'][0]
return json2obj(json.dumps(response))
def resolve_all(self, info, serial):
response = api_call('devices/?serial=%s' % serial)['results'][0]
return json2obj(json.dumps(response))
我需要做的查询是这样的:
query {
all(serial:201002000856){
device{
id
serial
reference
}
installation{
company
device
}
}
}
所以,我的问题是如何与这两种类型建立关系,如AllDataType
中所述,resolve_installation
需要device id
而resolve_all
需要序列号设备。
要解决安装问题,我需要device id
解析器返回的resolve_all
。
我怎样才能做到这一点?
答案 0 :(得分:1)
resolve_
中的Query
方法需要返回正确的数据类型,如Query
中所定义。例如,resolve_all
应返回AllDataType
个对象。因此,您需要获取api_call
方法的结果来构建AllDataType
和InstallationType
个对象。下面是一个示例,其中包含一些从REST获取的数据中获取设备和安装的方法:
def resolve_all(self, info, serial):
response = api_call('devices/?serial=%s' % serial)['results'][0]
# need to process the response to get the values you need
device = get_device_from_response(response)
installation = get_installation_from_response(response)
return AllDataType(device=device, installation=installation)
您可能还需要将解析方法添加到Type类中。有一个例子here。