Graphene: customizing how Enum is serialized

255 Views Asked by At

Our backend uses SQLAlchemy as our ORM, and I've recently been playing around with exposing a graphql API, but am having a hard time figuring out how to customize how Enum is serialized by graphene.

Our SqlAlchemy objects all inherit from a BaseModel we've written, and we've created our own BaseEnum that all db.Enum fields inherit, which we use to customize the fields included in a payload to the client, which is as follows,

someEnum: {
    'value': <some_value>,
    'label': <some_label>,
}

I haven't been able to figure out how to get graphene to do the same serialization (or if it is even possible/violates the spirit of grapqhl). Since these Enums are stored in our database as strings like THE_ENUM_VALUE, this is all graphene returns.

So I suppose I have two questions:

  1. Is this even the correct way to return this kind of payload with graphql? Or would it be more proper to have a query like
{
  someModel {
    someEnum {
      label
      value
    }
  }
}
  1. How would I override the serialization of all Enum fields returned by graphene so we don't have to write custom resolvers for every single Enum field? (there are hundreds)
1

There are 1 best solutions below

0
On

For everyone looking for an answer for the second question:

class MyEnum(graphene.Enum,):
    value: <some_value>,
    label: <some_label>,

    @property
    def description(self):
        return self.value