debian-mirror-gitlab/app/graphql/types/base_field.rb

88 lines
2.6 KiB
Ruby
Raw Normal View History

2018-12-05 23:21:45 +05:30
# frozen_string_literal: true
2018-11-08 19:23:39 +05:30
module Types
class BaseField < GraphQL::Schema::Field
prepend Gitlab::Graphql::Authorize
2019-07-07 11:18:12 +05:30
DEFAULT_COMPLEXITY = 1
def initialize(*args, **kwargs, &block)
2019-09-30 21:07:59 +05:30
@calls_gitaly = !!kwargs.delete(:calls_gitaly)
@constant_complexity = !!kwargs[:complexity]
2019-07-31 22:56:46 +05:30
kwargs[:complexity] ||= field_complexity(kwargs[:resolver_class])
2020-03-13 15:44:24 +05:30
@feature_flag = kwargs[:feature_flag]
kwargs = check_feature_flag(kwargs)
2019-07-07 11:18:12 +05:30
super(*args, **kwargs, &block)
end
2019-07-31 22:56:46 +05:30
2019-09-30 21:07:59 +05:30
def base_complexity
complexity = DEFAULT_COMPLEXITY
complexity += 1 if calls_gitaly?
complexity
end
def calls_gitaly?
@calls_gitaly
end
def constant_complexity?
@constant_complexity
end
2020-03-13 15:44:24 +05:30
def visible?(context)
return false if feature_flag.present? && !Feature.enabled?(feature_flag)
super
end
2019-07-31 22:56:46 +05:30
private
2020-03-13 15:44:24 +05:30
attr_reader :feature_flag
def feature_documentation_message(key, description)
"#{description}. Available only when feature flag #{key} is enabled."
end
def check_feature_flag(args)
args[:description] = feature_documentation_message(args[:feature_flag], args[:description]) if args[:feature_flag].present?
args.delete(:feature_flag)
args
end
2019-07-31 22:56:46 +05:30
def field_complexity(resolver_class)
if resolver_class
field_resolver_complexity
else
2019-09-30 21:07:59 +05:30
base_complexity
2019-07-31 22:56:46 +05:30
end
end
def field_resolver_complexity
# Complexity can be either integer or proc. If proc is used then it's
# called when computing a query complexity and context and query
# arguments are available for computing complexity. For resolvers we use
# proc because we set complexity depending on arguments and number of
# items which can be loaded.
proc do |ctx, args, child_complexity|
# Resolvers may add extra complexity depending on used arguments
2019-09-04 21:01:54 +05:30
complexity = child_complexity + self.resolver&.try(:resolver_complexity, args, child_complexity: child_complexity).to_i
2019-09-30 21:07:59 +05:30
complexity += 1 if calls_gitaly?
2019-09-04 21:01:54 +05:30
field_defn = to_graphql
2019-07-31 22:56:46 +05:30
2019-09-04 21:01:54 +05:30
if field_defn.connection?
# Resolvers may add extra complexity depending on number of items being loaded.
page_size = field_defn.connection_max_page_size || ctx.schema.default_max_page_size
limit_value = [args[:first], args[:last], page_size].compact.min
multiplier = self.resolver&.try(:complexity_multiplier, args).to_f
complexity += complexity * limit_value * multiplier
end
2019-07-31 22:56:46 +05:30
complexity.to_i
end
end
2018-11-08 19:23:39 +05:30
end
end