Module: WebFetch::HTTPHelpers

Included in:
Server
Defined in:
lib/web_fetch/http_helpers.rb

Overview

Convenience methods for WebFetch HTTP layer

Instance Method Summary collapse

Instance Method Details

#accept_gzip?Boolean

Returns:

  • (Boolean)


73
74
75
76
# File 'lib/web_fetch/http_helpers.rb', line 73

def accept_gzip?
  # em-http-request doesn't do us any favours with parsing the HTTP headers
  @http_headers.downcase.include?('accept-encoding: gzip')
end

#compress(string) ⇒ Object



12
13
14
15
16
# File 'lib/web_fetch/http_helpers.rb', line 12

def compress(string)
  return string unless accept_gzip?

  ActiveSupport::Gzip.compress(string)
end

#default_headers(response) ⇒ Object



18
19
20
21
22
23
# File 'lib/web_fetch/http_helpers.rb', line 18

def default_headers(response)
  response.headers['Content-Type'] = 'application/json; charset=utf-8'
  response.headers['Cache-Control'] = 'max-age=0, private, must-revalidate'
  response.headers['Content-Encoding'] = 'gzip' if accept_gzip?
  response.headers['Vary'] = 'Accept-Encoding'
end

#fail_(deferred, response) ⇒ Object



55
56
57
58
59
# File 'lib/web_fetch/http_helpers.rb', line 55

def fail_(deferred, response)
  response.status = 200
  response.content = compress(JSON.dump(failure(deferred)))
  response.send_response
end

#failure(deferred) ⇒ Object



61
62
63
64
65
66
67
68
69
70
71
# File 'lib/web_fetch/http_helpers.rb', line 61

def failure(deferred)
  result = deferred[:http]
  { response: {
    success: false,
    body: result.response,
    headers: result.headers,
    status: result.response_header.status,
    error: (result.error&.inspect)
  },
    uid: deferred[:uid] }
end

#post_dataObject



32
33
34
35
36
# File 'lib/web_fetch/http_helpers.rb', line 32

def post_data
  return nil unless @http_post_content

  JSON.parse(@http_post_content, symbolize_names: true)
end

#request_paramsObject



25
26
27
28
29
30
# File 'lib/web_fetch/http_helpers.rb', line 25

def request_params
  { method: @http_request_method,
    query_string: @http_query_string,
    post_data: post_data,
    server: self }
end

#respond_immediately(result, response) ⇒ Object



6
7
8
9
10
# File 'lib/web_fetch/http_helpers.rb', line 6

def respond_immediately(result, response)
  response.status = result[:status]
  response.content = compress(result[:payload].to_json)
  response.send_response
end

#succeed(deferred, response) ⇒ Object



38
39
40
41
42
# File 'lib/web_fetch/http_helpers.rb', line 38

def succeed(deferred, response)
  response.status = 200
  response.content = compress(JSON.dump(success(deferred)))
  response.send_response
end

#success(deferred) ⇒ Object



44
45
46
47
48
49
50
51
52
53
# File 'lib/web_fetch/http_helpers.rb', line 44

def success(deferred)
  result = deferred[:http]
  { response: {
    success: true,
    body: result.response,
    headers: result.headers,
    status: result.response_header.status
  },
    uid: deferred[:uid] }
end