# frozen_string_literal: true module ErpIntegration module Fulfil # The `Query` class transforms where clauses and included fields into a # queryable object that Fulfil understands. # # @example # $ Query.new([:id, 'product.id'], [['id', '=', '100']]).to_json # # => {"fields":["id","product.id"],"filters":[["id","=","100"]]} # # The instance of the `Query` class is meant to be passed to `Faraday` or # a third-party vendor client (e.g. `Fulfil::Client`) that uses `Faraday`. # # `Faraday` will call the `.to_json` method before sending the data to Fulfil. # So, there is no need to explicitly call `.to_json` on the `Query` instance. # # @example # Faraday.post("/api-endpoint", Query.new([:id, 'product.id'], [WhereClause.new(key: :id, value: 100)])) class Query attr_reader :fields, :filters DEFAULT_FIELDS = %w[id].freeze # @param fields [Array] A list of fields for Fulfil. # @param filters [Array] A list of where clauses for Fulfil. def initialize(fields, filters, alternative_filters = []) @fields = (fields || DEFAULT_FIELDS).map(&:to_s).uniq @filters = (filters || []).map(&:to_filter).uniq @filters += alternative_filters.map(&:to_filter).uniq if alternative_filters&.any? end def to_json(*_object) { fields: @fields, filters: @filters }.to_json end end end end