/
base_mutation.rb
90 lines (73 loc) · 2.66 KB
/
base_mutation.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
module Mutations
class BaseMutation < GraphQL::Schema::RelayClassicMutation
class << self
def argument(*args, **kwargs, &block)
required = kwargs.key?(:required) ? kwargs[:required] : attribute_required?(args.first)
super(*args, **kwargs.except(:required), required: required, &block)
end
def resource_class(new_resource_class = nil)
if new_resource_class
@resource_class = new_resource_class
else
@resource_class ||= "::#{self.to_s.split('::')[-2].singularize}".safe_constantize
end
end
private
def attribute_required?(attribute)
GraphqlAttribute.for(resource_class).required?(attribute)
end
end
object_class Types::BaseObject
input_object_class Types::BaseInputObject
private
delegate :resource_class, to: :class
def authorize!(resource, action)
user = context[:current_user]
authorizer = Authorizer.new(user)
permission_name = resource.permission_name(action)
unless authorizer.can?(permission_name, resource)
raise GraphQL::ExecutionError.new(
_('Unauthorized. You do not have the required permission %s.') % permission_name
)
end
end
def validate_object(resource)
unless resource.is_a?(resource_class)
raise GraphQL::ExecutionError.new("Resource mismatch, expected #{resource_class.name}, got #{resource.class.name}")
end
end
def load_object_by(id:)
object = GraphQL::Batch.batch { ForemanGraphqlSchema.object_from_id(id, context) }
raise GraphQL::ExecutionError.new(_('Could not resolve ID.')) unless object
validate_object(object)
object
end
def save_object(resource)
User.as(context[:current_user]) do
errors = if resource.save
[]
else
map_errors_to_path(resource)
end
{
result_key => resource,
errors: errors,
}
end
end
def map_errors_to_path(resource)
resource.errors.map do |attribute, message|
{
path: ['attributes', attribute.to_s.camelize(:lower)],
message: message,
}
end
end
def result_key
keys = self.class.fields.select { |field_name, field| field.owner == self.class }.keys.map(&:to_sym)
raise GraphQL::ExecutionError.new("Could not detect result key for #{self.class}. Did you define a result field for the mutation?") unless keys.any?
raise GraphQL::ExecutionError.new("Could not detect result key for #{self.class}. Possible values are #{keys.to_sentence}.") if keys.size > 1
keys.first
end
end
end