Module: DeepUnrest::Write

Defined in:
lib/deep_unrest/write.rb

Class Method Summary collapse

Class Method Details

.addr_to_lodash_path(path_arr) ⇒ Object



176
177
178
179
180
181
182
183
184
185
186
187
# File 'lib/deep_unrest/write.rb', line 176

def self.addr_to_lodash_path(path_arr)
  lodash_path = []
  until path_arr.empty?
    segment = path_arr.shift
    if segment.match(/\[\]$/)
      idx = path_arr.shift
      segment = "#{segment.gsub('[]', '')}[#{idx}]"
    end
    lodash_path << segment
  end
  lodash_path.join('.')
end

.append_ar_paths(mappings) ⇒ Object



48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/deep_unrest/write.rb', line 48

def self.append_ar_paths(mappings)
  mappings.each do |item|
    item[:ar_addr] = []
    addr = [*item[:addr]]
    until addr.empty?
      segment = addr.shift
      item[:ar_addr] << segment if item[:ar_addr].empty?
      next unless segment == :include

      next_segment = "#{addr.shift.underscore}_attributes"
      addr.shift if addr[0].to_s == 'data[]'
      idx = (addr.shift if addr[0].is_a? Integer)
      next_segment += '[]' if idx
      item[:ar_addr] << next_segment
      item[:ar_addr] << idx if idx
    end
  end
end

.authorize_attributes(mappings, ctx) ⇒ Object



67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
# File 'lib/deep_unrest/write.rb', line 67

def self.authorize_attributes(mappings, ctx)
  unauthorized_items = []

  mappings.reject { |m| m[:scope_type] == :show }
          .reject { |m| m[:destroy] }
          .each do |item|
    attributes = item.dig(:query, :attributes) || {}
    resource = item[:resource]
    p = JSONAPI::RequestParser.new
    p.source_klass = resource
    opts = if item[:scope_type] == :create
             resource.creatable_fields(ctx)
           else
             resource.updatable_fields(ctx)
           end

    p.parse_params(resource, { attributes: attributes }, opts)[:attributes]
  rescue JSONAPI::Exceptions::ParameterNotAllowed
    unpermitted_keys = attributes.keys.map(&:underscore).map(&:to_sym) - opts
    item[:errors] = unpermitted_keys.each_with_object({}) do |attr_key, memo|
      memo[attr_key] = 'Unpermitted parameter'
    end
    unauthorized_items << item
  end

  return if unauthorized_items.blank?

  msg = serialize_errors(unauthorized_items)
  raise DeepUnrest::UnpermittedParams, msg
end

.build_mutation_bodies(mappings) ⇒ Object



98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
# File 'lib/deep_unrest/write.rb', line 98

def self.build_mutation_bodies(mappings)
  mappings.each_with_object({}) do |item, memo|
    # TODO: use pkey instead of "id"
    id = item.dig(:query, :id)
    next if id.blank?

    next_attrs = (item.dig(:query, :attributes) || {})
                 .deep_symbolize_keys
    update_body = { id: id,
                    deep_unrest_query_uuid: item.dig(:query, :uuid),
                    **DeepUnrest.deep_underscore_keys(next_attrs) }

    update_body[:_destroy] = true if item.dig(:query, :destroy)
    DeepUnrest.set_attr(memo, item[:ar_addr].clone, update_body)
    if item[:ar_addr].size == 1
      item[:mutate] = memo.fetch(*item[:ar_addr])
      item[:scope_type] = :update if item[:scope_type] == :show
    end
  end
end

.create_mapping_sequence(k, v, addr) ⇒ Object



30
31
32
33
34
# File 'lib/deep_unrest/write.rb', line 30

def self.create_mapping_sequence(k, v, addr)
  v[:data].each_with_index.map do |item, idx|
    create_write_mapping(k, item, addr, idx)
  end
end

.create_write_mapping(k, v, addr, idx = nil) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/deep_unrest/write.rb', line 13

def self.create_write_mapping(k, v, addr, idx = nil)
  path = k
  resource_addr = [*addr, path]
  resource_addr += ['data[]', idx] if idx
  uuid = SecureRandom.uuid
  v[:uuid] = uuid
  [{ klass: k.singularize.classify.constantize,
     policy: "#{k.singularize.classify}Policy".constantize,
     resource: "#{k.singularize.classify}Resource".constantize,
     scope_type: get_scope_type(v, path),
     addr: resource_addr,
     key: k.camelize(:lower),
     uuid: uuid,
     query: v },
   *create_write_mappings(v[:include], [*resource_addr, :include])]
end

.create_write_mappings(params, addr = []) ⇒ Object



36
37
38
39
40
41
42
43
44
45
46
# File 'lib/deep_unrest/write.rb', line 36

def self.create_write_mappings(params, addr = [])
  return unless params

  params.map do |k, v|
    if v[:data] && v[:data].is_a?(Array)
      create_mapping_sequence(k, v, addr)
    else
      create_write_mapping(k, v, addr)
    end
  end.flatten.compact
end

.execute_queries(mappings, context) ⇒ Object



119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
# File 'lib/deep_unrest/write.rb', line 119

def self.execute_queries(mappings, context)
  ActiveRecord::Base.transaction do
    mappings.select { |m| m[:mutate] }.map do |item|
      record = case item[:scope_type]
               when :update
                 model = item[:klass].find(item.dig(:query, :id))
                 model.assign_attributes(item[:mutate])
                 resource = item[:resource].new(model, context)
                 resource.run_callbacks :save do
                   resource.run_callbacks :update do
                     model.save
                     model
                   end
                 end
               when :create
                 model = item[:klass].new(item[:mutate])
                 resource = item[:resource].new(model, context)
                 resource.run_callbacks :save do
                   resource.run_callbacks :create do
                     resource._model.save
                     resource._model
                   end
                 end
               when :destroy
                 id = item.dig(:query, :id)
                 model = item[:klass].find(id)
                 resource = item[:resource].new(model, context)
                 resource.run_callbacks :remove do
                   item[:klass].destroy(id)
                 end
               end

      item[:record] = record
      result = { record: record }
      if item[:temp_id]
        result[:temp_ids] = {}
        result[:temp_ids][item[:temp_id]] = record.id
      end
      result
    end
  end
end

.format_ar_error_path(base, ar_path) ⇒ Object



209
210
211
212
213
214
215
216
217
218
219
220
221
222
# File 'lib/deep_unrest/write.rb', line 209

def self.format_ar_error_path(base, ar_path)
  path_arr = ar_path.gsub(/\.(?!\w+$)/, '.include.')
                    .gsub(/\.(?=\w+$)/, '.attributes.\1')
                    .gsub(/\[(\d+)\]/, '.data[].\1')
                    .split('.')

  if path_arr.size == 1
    path_arr.unshift('attributes')
  elsif path_arr.size > 1
    path_arr.unshift('include')
  end

  [*base, *path_arr]
end

.get_scope_type(item, path) ⇒ Object



5
6
7
8
9
10
11
# File 'lib/deep_unrest/write.rb', line 5

def self.get_scope_type(item, path)
  return :destroy if item[:destroy]
  return :show if item[:readOnly] || item[:attributes].blank?
  return :create if item[:id] && DeepUnrest.temp_id?(item[:id].to_s)

  :update
end

.map_ar_errors_to_param_keys(mappings) ⇒ Object



224
225
226
227
228
229
230
231
232
233
234
# File 'lib/deep_unrest/write.rb', line 224

def self.map_ar_errors_to_param_keys(mappings)
  DeepUnrest.deep_camelize_keys(
    mappings
      .each_with_object({}) do |item, memo|
        item[:record]&.errors&.messages&.each do |ar_path, msg|
          err_path = format_ar_error_path(item[:addr], ar_path.to_s)
          DeepUnrest.set_attr(memo, err_path, msg)
        end
      end
  )
end

.serialize_changes(ctx, mappings, changed) ⇒ Object



162
163
164
165
166
167
168
169
170
171
172
173
174
# File 'lib/deep_unrest/write.rb', line 162

def self.serialize_changes(ctx, mappings, changed)
  changed.select { |c| c[:query_uuid] }
         .each_with_object({}) do |c, memo|
           mapping = mappings.find { |m| m.dig(:query, :uuid) == c[:query_uuid] }
           next if !mapping || mapping[:addr].blank?

           mapping[:query][:fields] = c[:attributes].keys
           mapping[:record] = c[:klass].new(id: c[:id])
           mapping[:record].assign_attributes(c[:attributes])
           result = DeepUnrest.serialize_result(ctx, mapping)
           DeepUnrest.set_attr(memo, mapping[:addr].clone, result)
         end
end

.serialize_destroyed(_ctx, mappings, destroyed) ⇒ Object



189
190
191
192
193
194
195
196
# File 'lib/deep_unrest/write.rb', line 189

def self.serialize_destroyed(_ctx, mappings, destroyed)
  destroyed.select { |d| d[:query_uuid] }
           .map do |d|
    mapping = mappings.find { |m| m.dig(:query, :uuid) == d[:query_uuid] }
    lodash_path = addr_to_lodash_path(mapping[:addr])
    { id: d[:id], path: lodash_path, type: mapping[:key].pluralize }
  end
end

.serialize_errors(mappings) ⇒ Object



198
199
200
201
202
203
204
205
206
207
# File 'lib/deep_unrest/write.rb', line 198

def self.serialize_errors(mappings)
  { errors: mappings.each_with_object({}) do |item, memo|
    err = {
      id: item.dig(:query, :id),
      type: item.dig(:query, :type),
      attributes: item[:errors,]
    }
    DeepUnrest.set_attr(memo, [*item[:addr]], err)
  end }.to_json
end

.write(ctx, params, user) ⇒ Object



236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
# File 'lib/deep_unrest/write.rb', line 236

def self.write(ctx, params, user)
  temp_id_map = DeepUnrest::ApplicationController.class_variable_get(
    '@@temp_ids'
  )
  temp_id_map[ctx[:uuid]] ||= {}

  # create mappings for assembly / disassembly
  mappings = create_write_mappings(params.to_unsafe_h)

  # authorize user for requested scope(s)
  DeepUnrest.authorization_strategy.authorize(mappings, user)

  authorize_attributes(mappings, ctx)

  # collect authorized scopes
  # DeepUnrest.collect_authorized_scopes(mappings, user)
  append_ar_paths(mappings)

  # bulid update arguments
  build_mutation_bodies(mappings)

  # convert temp_ids from ids to non-activerecord attributes
  DeepUnrest.convert_temp_ids!(ctx[:uuid], mappings.select { |m| m[:mutate] })

  # save data, run callbaks
  results = execute_queries(mappings, ctx)

  # check results for errors
  errors = results.map { |res| DeepUnrest.format_error_keys(res) }
                  .compact
                  .reject(&:empty?)
                  .compact

  if errors.empty?
    destroyed = DeepUnrest::ApplicationController.class_variable_get(
      '@@destroyed_entities'
    )

    changed = DeepUnrest::ApplicationController.class_variable_get(
      '@@changed_entities'
    )

    return {
      temp_ids: temp_id_map[ctx[:uuid]],
      destroyed: serialize_destroyed(ctx, mappings, destroyed),
      changed: serialize_changes(ctx, mappings, changed)
    }
  end

  # map errors to their sources
  formatted_errors = { errors: map_ar_errors_to_param_keys(mappings) }

  # raise error if there are any errors
  raise DeepUnrest::Conflict, formatted_errors.to_json
end