Module: WebFetch::HTTPHelpers

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

Overview

Convenience methods for WebFetch HTTP layer

Instance Method Summary collapse

Instance Method Details

#accept_gzip?Boolean

Returns:

  • (Boolean)


62
63
64
65
# File 'lib/web_fetch/concerns/http_helpers.rb', line 62

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



22
23
24
25
26
# File 'lib/web_fetch/concerns/http_helpers.rb', line 22

def compress(string)
  return string unless accept_gzip?

  ActiveSupport::Gzip.compress(string)
end

#default_headers(response) ⇒ Object



28
29
30
31
32
33
# File 'lib/web_fetch/concerns/http_helpers.rb', line 28

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_(resource, response) ⇒ Object



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

def fail_(resource, response)
  response.status = 200
  response.content = compress(JSON.dump(resource))
  storage.delete(resource[:request][:uid])
  response.send_response
end

#pending(uid, response) ⇒ Object



12
13
14
15
16
17
18
19
20
# File 'lib/web_fetch/concerns/http_helpers.rb', line 12

def pending(uid, response)
  respond_immediately({
                        payload: {
                          uid: uid,
                          pending: true,
                          message: I18n.t(:pending)
                        }
                      }, response)
end

#post_dataObject



42
43
44
45
46
# File 'lib/web_fetch/concerns/http_helpers.rb', line 42

def post_data
  return nil unless @http_post_content

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

#request_paramsObject



35
36
37
38
39
40
# File 'lib/web_fetch/concerns/http_helpers.rb', line 35

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/concerns/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(resource, response) ⇒ Object



48
49
50
51
52
53
# File 'lib/web_fetch/concerns/http_helpers.rb', line 48

def succeed(resource, response)
  response.status = 200
  response.content = compress(JSON.dump(resource))
  storage.delete(resource[:request][:uid])
  response.send_response
end