Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Include url helpers in graphql-ruby resolvers

I'm trying to access url helpers from resolve methods in graphql-ruby to generate fields like url. I know I can do this:

EventType = GraphQL::ObjectType.define do
  field :url, !types.String do
    resolve ->(event, _args, _ctx) do
      Rails.application.routes.url_helpers.event_path event
    end
  end
end

I know it's possible to include Rails.application.routes.url_helpers in your models to avoid prefixing every call but how to do this with graphql-ruby?

Additionally, if I call event_url, it doesn't have host and port. Obviously, I'd like to avoid adding host: request.host to every helper call.

like image 782
Petr Bela Avatar asked Feb 06 '23 04:02

Petr Bela


1 Answers

I've solved it by creating config/initializers/graphql.rb that injects url_helpers into the resolver's context:

module GraphQL
  module Define
    class DefinedObjectProxy
      include Rails.application.routes.url_helpers
    end
  end
end

As for the host and port, it looks like

# Allow to build url from models or graphql without needing to pass host/port every time
Rails.application.routes.default_url_options = Rails.application.config.action_mailer.default_url_options

does the trick. I've inserted this into a separate initializer although I suspect adding it to config/routes.rb would work, too.

like image 95
Petr Bela Avatar answered Feb 15 '23 22:02

Petr Bela