Sha256: b968194eeeef8f0066c08861226b2a3861458140e3ec7faaa7502bddb735e74e

Contents?: true

Size: 1.12 KB

Versions: 1

Compression:

Stored size: 1.12 KB

Contents

require 'rest-core/middleware'

require 'rest-client'
require 'em-http-request'

class RestCore::EmHttpRequestAsync
  include RestCore::Middleware
  def call env
    payload = ::RestClient::Payload.generate(env[REQUEST_PAYLOAD])
    client  = ::EventMachine::HttpRequest.new(request_uri(env)).send(
                 env[REQUEST_METHOD],
                 :body => payload.read,
                 :head => payload.headers.merge(env[REQUEST_HEADERS]))

    client.callback{ respond(env, client) }
    client. errback{ respond(env, client) }

    env[TIMER].on_timeout{
      client.close
      env[ASYNC].call(env.merge(RESPONSE_BODY    => env[TIMER].error,
                                RESPONSE_STATUS  => 0               ,
                                RESPONSE_HEADERS => {}             )) if
         env[ASYNC]
    } if env[TIMER]

    env
  end

  def respond env, client
    env[TIMER].cancel if env[TIMER] && !env[TIMER].canceled?
    env[ASYNC].call(env.merge(
      RESPONSE_BODY    => client.response,
      RESPONSE_STATUS  => client.response_header.status,
      RESPONSE_HEADERS => client.response_header)) if env[ASYNC]
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
rest-core-1.0.2 lib/rest-core/app/em-http-request-async.rb