-
Notifications
You must be signed in to change notification settings - Fork 0
/
base.rb
98 lines (77 loc) · 2.3 KB
/
base.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
module Rack
class Transform
module Transformers
module Base
class Request
CONTENT_TYPE = "CONTENT_TYPE".freeze
CONTENT_LENGTH = "CONTENT_LENGTH".freeze
POST_BODY = "rack.input".freeze
JSON_TYPE = "application/json".freeze
def self.call(env)
new(env).process
end
attr_reader :env
def initialize(env)
@env = env
end
def process
raise NotImplementedError
end
private
def req
@req ||= Rack::Request.new(env)
end
def params
req.params
end
def update_env(path:, query:, method:, body:)
body = body.is_a?(String) ? body : dump_json(body)
env.update(
Rack::PATH_INFO => path,
Rack::QUERY_STRING => query,
Rack::REQUEST_METHOD => method,
CONTENT_TYPE => JSON_TYPE,
CONTENT_LENGTH => body.bytesize,
POST_BODY => StringIO.new(body)
)
end
def dump_json(data)
JSON.dump(data)
end
end
class Response
CONTENT_LENGTH = "Content-Length".freeze
CONTENT_TYPE = "Content-Type".freeze
JSON_TYPE = "application/json".freeze
def self.call(status, header, body)
new(status, header, body).process
end
attr_reader :status, :header, :body
def initialize(status, header, body)
@status = status
@header = header.merge CONTENT_TYPE => JSON_TYPE
@body = body
end
def process
raise NotImplementedError
end
private
def respond_with(body, status: 200, header: @header)
formatted_body = body.is_a?(String) ? body : dump_json(body)
header[CONTENT_LENGTH] = formatted_body.bytesize.to_s
[status, header, [formatted_body]]
end
def parsed_body
@parsed_body ||= body.empty? ? [] : load_json(body.first)
end
def dump_json(data)
JSON.dump(data)
end
def load_json(data)
JSON.load(data)
end
end
end
end
end
end