Class: HasHelpers::Mutations::ExternalDataSync

Inherits:
Base
  • Object
show all
Defined in:
app/graphql/has_helpers/mutations/external_data_sync.rb

Instance Method Summary collapse

Methods included from HasHelpers::Middleware::ApplicationAccess

#authorized?

Instance Method Details

#resolve(resource:, data:, is_destroyed:, dependencies: []) ⇒ Object



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
# File 'app/graphql/has_helpers/mutations/external_data_sync.rb', line 14

def resolve(resource:, data:, is_destroyed:, dependencies: [])
  unless HasHelpers::SyncUtils.dependencies_satisfied?(data, dependencies)
    return { status: "retry", error: nil }
  end

  klass = ::ActiveRecord::Base.descendants.find do |model|
    # In modern Rails, ActiveRecord::Base.descendants can include anonymous or inner classes whose name is nil,
    # and doing model.name.demodulize will cause it to explode with an undefined method 'demodulize' for nil.
    model_name = model.name
    model_name.present? && model_name.demodulize.casecmp?(resource.demodulize)
  end

  unless klass
    resource_id = payload_id(data)
    return {
      status: "fail",
      error: "Could not resolve ActiveRecord class for resource=#{resource}, id=#{resource_id}"
    }
  end

  record = klass.find_or_initialize_by(id: payload_id(data))

  result = HasHelpers::SyncUtils.apply_mapping(
    record,
    data,
    resource_key: resource.underscore.to_sym,
    is_destroyed: is_destroyed
  )

  case result
  when true
    HasHelpers::SyncUtils.touch_dependencies!(data, dependencies)
    { status: "ok", error: nil }
  when String
    { status: "fail", error: result }
  else
    {
      status: "fail",
      error: mapping_result_error(resource: resource, data: data, result: result)
    }
  end
rescue => e
  # wrap in GraphQL::ExecutionError so unhandled exceptions return a JSON errors payload
  # instead of a pink-screen, which the caller GoodJob::SyncDataToApps can't parse.
  raise GraphQL::ExecutionError, "ExternalDataSync failed for #{resource}: #{e.message}"
end