Skip to content

Commit

Permalink
Add conversions to query model
Browse files Browse the repository at this point in the history
  • Loading branch information
swanny85 committed Jan 4, 2024
1 parent 4a52e04 commit 570a74a
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 2 deletions.
21 changes: 19 additions & 2 deletions lib/fulfil/query.rb
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
# frozen_string_literal: true

require 'date'
require 'fulfil/converter'

module Fulfil
class Query
def initialize
Expand Down Expand Up @@ -86,11 +89,25 @@ def build_search_term(field:, value:, options:, prefix: nil)
[[key, 'ilike', value]]
end
when 'Hash'
handle_hash(field, key, value, options)
when 'Date', 'DateTime'
[[key, '=', Converter.date_or_datetime_as_object(value)]]
else
raise "Unhandled value type: #{value} (#{value.class.name})"
end
end

def handle_hash(field, key, value, options)
if %i[gte gt lte lt].any? { |op| value.key?(op) }
value.map do |operator, val|
op_map = { gte: '>=', gt: '>', lte: '<=', lt: '<' }
converted_value = Converter.date_or_datetime_as_object(val)
[key, op_map[operator], converted_value]
end
else
value.flat_map do |nested_field, nested_value|
build_search_term(prefix: field, field: nested_field, value: nested_value, options: options)
end
else
raise "Unhandled value type: #{value} (#{value.class.name})"
end
end

Expand Down
30 changes: 30 additions & 0 deletions test/fulfil/query_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,10 @@

require 'minitest/autorun'
require 'fulfil/query'
require 'fulfil/converter'
require 'date'

# rubocop:disable Metrics/ClassLength
module Fulfil
class QueryTest < Minitest::Test
def setup
Expand Down Expand Up @@ -47,6 +50,32 @@ def test_nested_queries
assert_equal [['sale.id', 'in', [123]]], @query.query
end

def test_dates_are_converted_to_iso8601
date = Date.new(2019, 1, 1)
expected_date_format = Converter.date_as_object(date)

@query.search(date: date)

assert_equal [['date', '=', expected_date_format]], @query.query
end

def test_date_greater_than_or_equal_to_converted_to_iso8601
date = Date.new(2019, 1, 1)
expected_date_format = Converter.date_as_object(date)

@query.search(date: { gte: date })

assert_equal [['date', '>=', expected_date_format]], @query.query
end

def test_datetime_less_than_converted_to_iso8601
datetime = DateTime.new(2019, 1, 1, 0, 0, 0)
expected_datetime_format = Converter.datetime_as_object(datetime)

@query.search(datetime: { lt: datetime })

assert_equal [['datetime', '<', expected_datetime_format]], @query.query
end
# -- #exclude -----------------------

def test_equals_exclude
Expand Down Expand Up @@ -183,3 +212,4 @@ def test_chaining
end
end
end
# rubocop:enable Metrics/ClassLength

0 comments on commit 570a74a

Please sign in to comment.