使用 RESTfull API 作为数据源的石墨烯关系

graphene relation using RESTfull API as data source

我正在使用 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 idresolve_all 需要一个设备序列号。

要解析安装,我需要 resolve_all 解析器返回的 device id

我怎样才能做到这一点?

Query 中的 resolve_ 方法需要 return 正确的数据类型,如 Query 中所定义。例如,resolve_all 应该 return 一个 AllDataType 对象。因此,您需要使用 api_call 方法的结果来构建 AllDataTypeInstallationType 对象。这是一个示例,其中包含一些从 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)

您可能还需要为您的类型添加解析方法 类。有一个例子 .