0

我正在使用 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
        }
    }
}

所以,我的问题是如何与这两种类型建立关系,如 中所述AllDataTyperesolve_installation需要device idresolve_all需要设备的序列号。

要解决安装,我需要解析器device id返回的内容。resolve_all

我怎样才能做到这一点?

4

1 回答 1

1

需要返回正确类型的数据的方法,resolve_如. 例如,应该返回一个对象。因此,您需要将方法的结果用于构建和对象。这是一个示例,其中包含一些从 REST 获取的数据中获取设备和安装的方法:QueryQueryresolve_allAllDataTypeapi_callAllDataTypeInstallationType

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)

您可能还需要将解析方法添加到您的类型类。这里有一个例子。

于 2018-01-31T20:49:06.017 回答