diff --git a/lib/fulfil/query.rb b/lib/fulfil/query.rb index 2218e91..54435a9 100644 --- a/lib/fulfil/query.rb +++ b/lib/fulfil/query.rb @@ -1,5 +1,8 @@ # frozen_string_literal: true +require 'date' +require 'fulfil/converter' + module Fulfil class Query def initialize @@ -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 diff --git a/test/fulfil/query_test.rb b/test/fulfil/query_test.rb index de7bc28..231e58e 100644 --- a/test/fulfil/query_test.rb +++ b/test/fulfil/query_test.rb @@ -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 @@ -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 @@ -183,3 +212,4 @@ def test_chaining end end end +# rubocop:enable Metrics/ClassLength