Skip to content

Commit

Permalink
feat(felixible aggregation): Add documentation for expression evaluat…
Browse files Browse the repository at this point in the history
…ion endpoint
  • Loading branch information
vincent-pochet committed Oct 24, 2024
1 parent 7c795f4 commit ce23528
Show file tree
Hide file tree
Showing 3 changed files with 59 additions and 0 deletions.
22 changes: 22 additions & 0 deletions lib/lago/api/resources/billable_metric.rb
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,15 @@ def root_name
'billable_metric'
end

def evaluate_expression(params)
uri = URI("#{client.base_api_url}#{api_resource}/evaluate_expression")

payload = whitelist_evalute_expression_params(params)
response = connection.post(payload, uri)['expression_result']

JSON.parse(response.to_json, object_class: OpenStruct)
end

def whitelist_params(params)
{
root_name => {
Expand All @@ -27,6 +36,19 @@ def whitelist_params(params)
}.compact,
}
end

def whitelist_evalute_expression_params(params)
event = params[:event] || {}

{
expression: params[:expression],
event: {
code: event[:code],
timestamp: event[:timestamp],
properties: event[:properties],
}.compact,
}
end
end
end
end
Expand Down
5 changes: 5 additions & 0 deletions spec/fixtures/api/billable_metric_evaluate_expression.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"expression_result": {
"value": "2.0"
}
}
32 changes: 32 additions & 0 deletions spec/lago/api/resources/billable_metric_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -187,4 +187,36 @@
end
end
end

describe '#evaluate_expression' do
let(:expression) { 'round(event.properties.value * event.properties.units)' }
let(:event) { { properties: { value: 10, units: 2 } } }

let(:evaluate_expression_response) { load_fixture('billable_metric_evaluate_expression') }

context 'when expression is successfully evaluated' do
before do
stub_request(:post, 'https://api.getlago.com/api/v1/billable_metrics/evaluate_expression')
.with(body: { expression: expression, event: event })
.to_return(body: evaluate_expression_response, status: 200)
end

it 'returns the evaluation result' do
evaluation_result = resource.evaluate_expression(event: event, expression: expression)

expect(evaluation_result.value).to eq('2.0')
end
end

context 'when there is an issue' do
before do
stub_request(:post, 'https://api.getlago.com/api/v1/billable_metrics/evaluate_expression')
.to_return(body: error_response, status: 422)
end

it 'raises an error' do
expect { resource.evaluate_expression(event: event, expression: expression) }.to raise_error Lago::Api::HttpError
end
end
end
end

0 comments on commit ce23528

Please sign in to comment.