Module: DeepUnrest::Write
- Defined in:
- lib/deep_unrest/write.rb
Class Method Summary collapse
- .addr_to_lodash_path(path_arr) ⇒ Object
- .append_ar_paths(mappings) ⇒ Object
- .authorize_attributes(mappings, ctx) ⇒ Object
- .build_mutation_bodies(mappings) ⇒ Object
- .create_mapping_sequence(k, v, addr) ⇒ Object
- .create_write_mapping(k, v, addr, idx = nil) ⇒ Object
- .create_write_mappings(params, addr = []) ⇒ Object
- .execute_queries(mappings, context) ⇒ Object
- .format_ar_error_path(base, ar_path) ⇒ Object
- .get_scope_type(item) ⇒ Object
- .map_ar_errors_to_param_keys(mappings) ⇒ Object
- .serialize_changes(ctx, mappings, changed) ⇒ Object
- .serialize_destroyed(_ctx, mappings, destroyed) ⇒ Object
- .serialize_errors(mappings) ⇒ Object
- .write(ctx, params, user) ⇒ Object
Class Method Details
.addr_to_lodash_path(path_arr) ⇒ Object
170 171 172 173 174 175 176 177 178 179 180 181 |
# File 'lib/deep_unrest/write.rb', line 170 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.(mappings, ctx) = [] 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.resource_klass = resource opts = if item[:scope_type] == :create resource.creatable_fields(ctx) else resource.updatable_fields(ctx) end p.parse_params({ attributes: attributes }, opts)[:attributes] rescue JSONAPI::Exceptions::ParameterNotAllowed unpermitted_keys = attributes.keys.map(&:to_sym) - opts item[:errors] = unpermitted_keys.each_with_object({}) do |attr_key, memo| memo[attr_key] = 'Unpermitted parameter' end << item end return if .blank? msg = serialize_errors() 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 |
# 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" next_attrs = (item.dig(:query, :attributes) || {}) .deep_symbolize_keys update_body = { id: item.dig(:query, :id), deep_unrest_query_uuid: item.dig(:query, :uuid), **DeepUnrest.deep_underscore_keys(next_attrs) } update_body[:_destroy] = true if item[:scope_type] == :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), 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
115 116 117 118 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 |
# File 'lib/deep_unrest/write.rb', line 115 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 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
203 204 205 206 207 208 209 210 211 212 213 214 215 216 |
# File 'lib/deep_unrest/write.rb', line 203 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) ⇒ Object
5 6 7 8 9 10 11 |
# File 'lib/deep_unrest/write.rb', line 5 def self.get_scope_type(item) 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
218 219 220 221 222 223 224 225 226 |
# File 'lib/deep_unrest/write.rb', line 218 def self.map_ar_errors_to_param_keys(mappings) mappings .each_with_object({}) do |item, memo| item[:record]&.errors&.&.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
157 158 159 160 161 162 163 164 165 166 167 168 |
# File 'lib/deep_unrest/write.rb', line 157 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 unless mapping 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], result) end end |
.serialize_destroyed(_ctx, mappings, destroyed) ⇒ Object
183 184 185 186 187 188 189 190 |
# File 'lib/deep_unrest/write.rb', line 183 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
192 193 194 195 196 197 198 199 200 201 |
# File 'lib/deep_unrest/write.rb', line 192 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
228 229 230 231 232 233 234 235 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 |
# File 'lib/deep_unrest/write.rb', line 228 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..(mappings, user) (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 |