2019-02-15 15:39:39 +05:30
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2018-11-08 19:23:39 +05:30
|
|
|
module Gitlab
|
|
|
|
module Graphql
|
|
|
|
module Present
|
|
|
|
class Instrumentation
|
2021-01-29 00:20:46 +05:30
|
|
|
SAFE_CONTEXT_KEYS = %i[current_user].freeze
|
|
|
|
|
2018-11-08 19:23:39 +05:30
|
|
|
def instrument(type, field)
|
|
|
|
return field unless field.metadata[:type_class]
|
|
|
|
|
|
|
|
presented_in = field.metadata[:type_class].owner
|
|
|
|
return field unless presented_in.respond_to?(:presenter_class)
|
|
|
|
return field unless presented_in.presenter_class
|
|
|
|
|
|
|
|
old_resolver = field.resolve_proc
|
|
|
|
|
|
|
|
resolve_with_presenter = -> (presented_type, args, context) do
|
|
|
|
# We need to wrap the original presentation type into a type that
|
|
|
|
# uses the presenter as an object.
|
|
|
|
object = presented_type.object
|
|
|
|
|
|
|
|
if object.is_a?(presented_in.presenter_class)
|
|
|
|
next old_resolver.call(presented_type, args, context)
|
|
|
|
end
|
|
|
|
|
2021-01-29 00:20:46 +05:30
|
|
|
attrs = safe_context_values(context)
|
|
|
|
presenter = presented_in.presenter_class.new(object, **attrs)
|
2019-12-04 20:38:33 +05:30
|
|
|
|
|
|
|
# we have to use the new `authorized_new` method, as `new` is protected
|
|
|
|
wrapped = presented_type.class.authorized_new(presenter, context)
|
2018-11-08 19:23:39 +05:30
|
|
|
|
|
|
|
old_resolver.call(wrapped, args, context)
|
|
|
|
end
|
|
|
|
|
|
|
|
field.redefine do
|
|
|
|
resolve(resolve_with_presenter)
|
|
|
|
end
|
|
|
|
end
|
2021-01-29 00:20:46 +05:30
|
|
|
|
|
|
|
private
|
|
|
|
|
|
|
|
def safe_context_values(context)
|
|
|
|
context.to_h.slice(*SAFE_CONTEXT_KEYS)
|
|
|
|
end
|
2018-11-08 19:23:39 +05:30
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|