代码之家  ›  专栏  ›  技术社区  ›  cardoso

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

  •  0
  • cardoso  · 技术社区  · 7 年前

    我使用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 需要设备的序列号。

    要解决安装问题,我需要 设备id 返回人 resolve\u全部 分解器。

    我怎样才能做到这一点?

    1 回复  |  直到 7 年前
        1
  •  1
  •   Mark Chackerian    7 年前

    这个 resolve_ 中的方法 Query 需要返回正确类型的数据,如中所定义 查询 . 例如 resolve_all 应返回 AllDataType 对象所以你需要 api_call 要生成的方法 所有数据类型 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)
    

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