Sha256: b4800b2dd757d0bc42af0974364ada22647e9c00ca987b7fbe8bc9d25c8d96c5

Contents?: true

Size: 1.72 KB

Versions: 2

Compression:

Stored size: 1.72 KB

Contents

module Trailblazer
  class Operation
    def self.Finder(finder_class, action = nil, entity = nil)
      task = Trailblazer::Activity::Circuit::TaskAdapter.for_step(Finder.new, binary: true)
      injections = [
        :params,
        {:"finder.class" => ->(*) { finder_class }},
        {:"finder.entity" => ->(*) { entity }},
        {:"finder.action" => ->(*) { action }}
      ]

      {task: task, id: "finder.build", inject: injections}
    end

    class Finder
      def call(ctx, **options)
        builder = Finder::Builder.new
        ctx[:finder] = finder = builder.call(options, options[:params])
        ctx[:model] = finder # Don't like it, but somehow it's needed if contracts are loaded
        ctx[:"result.finder"] = Trailblazer::Operation::Result.new(!finder.nil?, {})

        ctx[:"result.finder"].success?
      end

      class Builder
        def call(options, params)
          finder_class = options[:"finder.class"]
          entity = options[:"finder.entity"]
          action = options[:"finder.action"]
          action = :all unless %i[all single].include?(action)

          send("#{action}!", finder_class, entity, params, options[:"finder.action"])
        end

        private

        def all!(finder_class, entity, params, *)
          finder_class.new(entity: entity, params: params)
        end

        def single!(finder_class, entity, params, *)
          apply_id(params)
          if entity.nil?
            finder_class.new(params: params).result.first
          else
            finder_class.new(entity: entity, params: params).result.first
          end
        end

        def apply_id(params)
          return if params[:id].nil?

          params[:id_eq] = params[:id]
        end
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
trailblazer-finder-0.92.0 lib/trailblazer/operation/finder.rb
trailblazer-finder-0.91.0 lib/trailblazer/operation/finder.rb