Sha256: 9d8c587712784daad103ce5d18edce80d8613829929755b34aa2189bb42e0756

Contents?: true

Size: 1.01 KB

Versions: 1

Compression:

Stored size: 1.01 KB

Contents

require 'rest-core/middleware'

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

class RestCore::EmHttpRequestFiber
  include RestCore::Middleware
  def call env
    f = Fiber.current

    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{
      env[TIMER].cancel if env[TIMER]
      f.resume(process(env, client)) if f.alive?
    }

    if (response = Fiber.yield).kind_of?(::Exception)
      client.close
      raise response
    else
      response
    end
  end

  def process env, client
    result = env.merge(RESPONSE_BODY    => client.response,
                       RESPONSE_STATUS  => client.response_header.status,
                       RESPONSE_HEADERS => client.response_header)
    result[ASYNC].call(result) if result[ASYNC]
    result
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
rest-core-1.0.0 lib/rest-core/app/em-http-request-fiber.rb