Class: Collavre::Tools::CreativeBatchService

Inherits:
Object
  • Object
show all
Extended by:
T::Sig, ToolMeta
Defined in:
app/services/collavre/tools/creative_batch_service.rb

Defined Under Namespace

Classes: BatchRollbackError

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.requires_approval?Boolean

Returns:

  • (Boolean)


16
17
18
# File 'app/services/collavre/tools/creative_batch_service.rb', line 16

def self.requires_approval?
  true
end

Instance Method Details

#call(operations:) ⇒ Object



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 'app/services/collavre/tools/creative_batch_service.rb', line 36

def call(operations:)
  raise "Current.user is required" unless Current.user

  results = []

  ApplicationRecord.transaction do
    operations.each_with_index do |op, idx|
      op = op.transform_keys(&:to_s)
      action = op["action"]

      result = case action
      when "create" then execute_create(op)
      when "update" then execute_update(op)
      when "delete" then execute_delete(op)
      else
                 { error: "Unknown action '#{action}'" }
      end

      result[:index] = idx
      result[:action] = action
      results << result

      raise BatchRollbackError, results if result[:error]
    end
  end

  { success: true, results: results }
rescue BatchRollbackError => e
  failed = e.results.find { |r| r[:error] }
  { success: false, error: "Operation #{failed[:index]} (#{failed[:action]}) failed: #{failed[:error]}", results: e.results }
end