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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With