Class: ForestAdminAgent::Routes::Resources::UpdateField

Inherits:
AbstractAuthenticatedRoute show all
Includes:
Builder, ForestAdminDatasourceToolkit::Components::Query, ForestAdminDatasourceToolkit::Schema, ForestAdminDatasourceToolkit::Validations
Defined in:
lib/forest_admin_agent/routes/resources/update_field.rb

Instance Method Summary collapse

Methods inherited from AbstractAuthenticatedRoute

#build, #format_attributes, #redacted_full_projection, #redacted_projection_with_pks

Methods inherited from AbstractRoute

#add_route, #build, #initialize, #routes

Constructor Details

This class inherits a constructor from ForestAdminAgent::Routes::AbstractRoute

Instance Method Details

#handle_request(args = {}) ⇒ Object



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
# File 'lib/forest_admin_agent/routes/resources/update_field.rb', line 25

def handle_request(args = {})
  context = build(args)

  primary_key_values = Utils::Id.unpack_id(context.collection, args[:params]['id'], with_key: true)
  field_name = args[:params]['field_name']
  array_index = parse_index(args[:params]['index'])

  context.permissions.can?(:edit, context.collection)

  field_schema = context.collection.schema[:fields][field_name]
  validate_array_field!(field_schema, field_name, context.collection)

  record = fetch_record(primary_key_values, context)

  array = record[field_name]
  validate_array_value!(array, field_name, array_index)

  new_value = parse_value_from_body(args[:params], field_schema)

  updated_array = array.dup
  updated_array[array_index] = new_value

  scope = context.permissions.get_scope(context.collection)
  condition_tree = ConditionTree::ConditionTreeFactory.match_records(context.collection, [primary_key_values])
  filter = ForestAdminDatasourceToolkit::Components::Query::Filter.new(
    condition_tree: ConditionTree::ConditionTreeFactory.intersect([condition_tree, scope])
  )
  context.collection.update(context.caller, filter, { field_name => updated_array })

  projection = redacted_full_projection(context)
  records = context.collection.list(context.caller, filter, projection)

  {
    name: args[:params]['collection_name'],
    content: JSONAPI::Serializer.serialize(
      records[0],
      is_collection: false,
      class_name: context.collection.name,
      serializer: Serializer::ForestSerializer
    )
  }
end

#setup_routesObject



14
15
16
17
18
19
20
21
22
23
# File 'lib/forest_admin_agent/routes/resources/update_field.rb', line 14

def setup_routes
  add_route(
    'forest_update_field',
    'put',
    '/:collection_name/:id/relationships/:field_name/:index',
    ->(args) { handle_request(args) }
  )

  self
end