Sha256: 229d7a817d5943ea6a936e9284e3eb3d777cb34df047e1e6e1984d42fa5af086

Contents?: true

Size: 1.14 KB

Versions: 2

Compression:

Stored size: 1.14 KB

Contents

require 'json'
require 'rack'

module RailsCloudTasks
  module Rack
    class Jobs
      class << self
        def call(env)
          job_class = extract_job_class(env)

          RailsCloudTasks::Instrumentation.transaction_name!(
            "RailsCloudTasks/#{job_class}/perform_now"
          )

          request = ::Rack::Request.new(env)
          job_args = extract_args(request)

          job_class.perform_now(*job_args)

          response(200, {})
        rescue Rack::InvalidPayloadError => e
          response(422, { error: e.message })
        rescue StandardError => e
          response(500, { error: e.message })
        end

        private

        def extract_job_class(env)
          env.dig('action_dispatch.request.path_parameters', :job_class)
             .constantize
        end

        def extract_args(request)
          body = request.body.read
          JSON.parse(body) || []
        rescue JSON::ParserError, KeyError
          raise Rack::InvalidPayloadError
        end

        def response(status, body)
          [status, { 'Content-Type' => 'application/json' }, [body.to_json]]
        end
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
rails-cloud-tasks-0.0.5 lib/rails_cloud_tasks/rack/jobs.rb
rails-cloud-tasks-0.0.4 lib/rails_cloud_tasks/rack/jobs.rb