Alias Method on a GraphQL Field
A lot of times I find I have to alias a method on a model when I'm exposing it on a GraphQL type. Most often I have to do this with ?
methods:
class Post < ApplicationRecord
def draft?
...
end
end
class PostType < GraphQL::Schema::Object
field :draft, Boolean, null: false
def draft
@object.draft?
end
end
I want the field to be draft
(without the ?
), but on it's own the GraphQL Ruby gem can't resolve it to draft?
, so I have to add an additional def in the Type class. This works, but it feels clunky.
Turns out you can use the method:
option on the field to alias it inline, which I think streamlines things:
class PostType < GraphQL::Schema::Object
field :draft, Boolean, null: false, method: :draft?
end
Tweet