Sha256: 2675f899879fe854adea8698731b45bb3275f755b98ec9db9a5c53fd31009345

Contents?: true

Size: 1.8 KB

Versions: 3

Compression:

Stored size: 1.8 KB

Contents

# 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
      delegate :to_json, to: :to_h

      attr_reader :fields, :filters, :offset, :limit

      DEFAULT_FIELDS = %w[id].freeze

      # @param fields [Array<String|Symbol>] A list of fields for Fulfil.
      # @param filters [Array<WhereClause>] A list of where clauses for Fulfil.
      # @param alternative_filters [Array<OrClause>] A list of or clauses for Fulfil.
      # @param offset [Integer] Offset for pagination.
      # @param limit [Integer] Limit for pagination.
      def initialize(fields:, filters:, alternative_filters: [], offset: nil, limit: nil)
        @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?
        @offset = offset
        @limit = limit
      end

      def to_h
        {
          fields: @fields,
          filters: @filters,
          offset: @offset,
          limit: @limit
        }
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
erp_integration-0.20.0 lib/erp_integration/fulfil/query.rb
erp_integration-0.19.0 lib/erp_integration/fulfil/query.rb
erp_integration-0.18.0 lib/erp_integration/fulfil/query.rb