Skip to content

How to share models for calling methods for different resolver? #473

Description

@ptrhck

This question is somewhat related to this issue: graphql-python/graphene#803

import graphene


class LocationData:
    def __init__(self, latitude, longitude, temperature):
        self.lat = latitude
        self.lng = longitude
        self.tmp = temperature

    def first_metric(self):
        return self.lat + self.lng

    def second_metric(self):
        return self.lat / self.tmp ** 2


class GeoInput(graphene.InputObjectType):
    lat = graphene.Float(required=True)
    lng = graphene.Float(required=True)
    tmp = graphene.Float(required=True)


class FirstField(graphene.ObjectType):
    first_metric = graphene.Float()


class SecondField(graphene.ObjectType):
    second_metric = graphene.Float()
    third_metric = graphene.Float()


class Query(graphene.ObjectType):
    first = graphene.Field(FirstField, geo=GeoInput(required=True))
    second = graphene.Field(SecondField, geo=GeoInput(required=True))

    def resolve_first(self, info, geo):
        data = LocationData(geo.lat, geo.lng, geo.tmp)
        return FirstField(first_metric=data.first_metric())

    def resolve_second(self, info, geo):
        data = LocationData(geo.lat, geo.lng, geo.tmp)
        value1 = data.second_metric()
        value2 = value1+300
        return SecondField(second_metric=value1,
                           third_metric=value2)

The query currently looks like this:

query{
  first(geo: {lat: 30, lng: 20, tmp:2}){
    firstMetric
  }
  second(geo: {lat: 30, lng: 20, tmp:2}){
    secondMetric
    thirdMetric
  }
}

Here, I am wondering how I can share my LocationData object such that it is initialized only once and than its methods available for both resolve functions? Like or similiar to this:

class Query(graphene.ObjectType):
    first = graphene.Field(FirstField, geo=GeoInput(required=True))
    second = graphene.Field(SecondField, geo=GeoInput(required=True))
    data = LocationData(geo.lat, geo.lng, geo.tmp)

    def resolve_first(self, info, geo):
        return FirstField(first_metric=self.data.first_metric())

    def resolve_second(self, info, geo):
        value1 = self.data.second_metric()
        value2 = value1+300
        return SecondField(second_metric=value1,
                           third_metric=value2)

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions