Sha256: 45a92a438c2bffa434123cea7615fada022d44de6833c15fa0c9f424b3418a55

Contents?: true

Size: 1.1 KB

Versions: 12

Compression:

Stored size: 1.1 KB

Contents

require 'faraday'
require 'json'

module Ably
  module Rest
    module Middleware
      # Encode the body of the message according to the mime type
      class Encoder < Faraday::Middleware
        CONTENT_TYPE = 'Content-Type'.freeze unless defined? CONTENT_TYPE

        def call(env)
          encode env if env.body
          @app.call env
        end

        private
        def encode(env)
          env.body = case request_type(env)
          when 'application/x-msgpack'
            to_msgpack(env.body)
          when 'application/json', '', nil
            env.request_headers[CONTENT_TYPE] = 'application/json'
            to_json(env.body)
          else
            env.body
          end
        end

        def to_msgpack(body)
          body.to_msgpack
        end

        def to_json(body)
          if body.kind_of?(String)
            body
          else
            body.to_json
          end
        end

        def request_type(env)
          type = env.request_headers[CONTENT_TYPE].to_s
          type = type.split(';', 2).first if type.index(';')
          type
        end
      end
    end
  end
end

Version data entries

12 entries across 12 versions & 2 rubygems

Version Path
ably-rest-1.2.7 lib/submodules/ably-ruby/lib/ably/rest/middleware/encoder.rb
ably-1.2.7 lib/ably/rest/middleware/encoder.rb
ably-rest-1.2.6 lib/submodules/ably-ruby/lib/ably/rest/middleware/encoder.rb
ably-1.2.6 lib/ably/rest/middleware/encoder.rb
ably-rest-1.2.4 lib/submodules/ably-ruby/lib/ably/rest/middleware/encoder.rb
ably-1.2.4 lib/ably/rest/middleware/encoder.rb
ably-rest-1.2.3 lib/submodules/ably-ruby/lib/ably/rest/middleware/encoder.rb
ably-1.2.3 lib/ably/rest/middleware/encoder.rb
ably-rest-1.2.2 lib/submodules/ably-ruby/lib/ably/rest/middleware/encoder.rb
ably-1.2.2 lib/ably/rest/middleware/encoder.rb
ably-rest-1.2.1 lib/submodules/ably-ruby/lib/ably/rest/middleware/encoder.rb
ably-1.2.1 lib/ably/rest/middleware/encoder.rb