Class: Squake::Calculation

Inherits:
Object
  • Object
show all
Extended by:
T::Sig
Defined in:
lib/squake/calculation.rb

Constant Summary collapse

ENDPOINT =
T.let('/v2/calculations', String)

Class Method Summary collapse

Class Method Details

.create(items:, carbon_unit: 'gram', expand: [], client: Squake::Client.new, request_id: nil) ⇒ Object



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
# File 'lib/squake/calculation.rb', line 20

def self.create(items:, carbon_unit: 'gram', expand: [], client: Squake::Client.new, request_id: nil)
  # @TODO: add typed objects for all possible items. Until then, we allow either a Hash or a T::Struct
  items = items.map do |item|
    item.is_a?(T::Struct) ? item.serialize : item
  end

  result = client.call(
    path: ENDPOINT,
    method: :post,
    headers: { 'X-Request-Id' => request_id }.compact,
    params: {
      items: items,
      carbon_unit: carbon_unit,
      expand: expand,
    },
  )

  if result.success?
    carbon = Squake::Model::Carbon.from_api_response(
      T.cast(result.body, T::Hash[Symbol, T.untyped]),
    )
    Return.new(result: carbon)
  else
    error = Squake::Errors::APIErrorResult.new(
      code: :"api_error_#{result.code}",
      detail: result.error_message,
    )
    Return.new(errors: [error])
  end
end