Sha256: 0c7370f9edd95b79585eef11f9ab9855c1bb896b253437d09dc08ee4f7419ecc

Contents?: true

Size: 1.21 KB

Versions: 1

Compression:

Stored size: 1.21 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)

          if job_args
            job_class.perform_now(job_args)
          else
            job_class.perform_now
          end

          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

1 entries across 1 versions & 1 rubygems

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