-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathmicrocms.rb
More file actions
180 lines (147 loc) · 4.37 KB
/
microcms.rb
File metadata and controls
180 lines (147 loc) · 4.37 KB
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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
# frozen_string_literal: true
require 'microcms/version'
require 'net/http'
require 'uri'
require 'json'
require 'forwardable'
# MicroCMS
module MicroCMS
class << self
extend Forwardable
attr_accessor :api_key, :service_domain
delegate %i[list get create update delete] => :client
def client
Client.new(@service_domain, @api_key)
end
end
# HttpUtil
module HttpUtil
def send_http_request(method, endpoint, path, query = nil, body = nil)
uri = build_uri(endpoint, path, query)
http = build_http(uri)
req = build_request(method, uri, body)
res = http.request(req)
raise APIError.new(status_code: res.code.to_i, body: res.body) if res.code.to_i >= 400
JSON.parse(res.body, object_class: OpenStruct) if res.header['Content-Type'].include?('application/json') # rubocop:disable Style/OpenStructUse
end
private
def get_request_class(method)
{
GET: Net::HTTP::Get,
POST: Net::HTTP::Post,
PUT: Net::HTTP::Put,
PATCH: Net::HTTP::Patch,
DELETE: Net::HTTP::Delete
}[method]
end
def build_request(method, uri, body)
req = get_request_class(method.to_sym).new(uri.request_uri)
req['X-MICROCMS-API-KEY'] = @api_key
if body
req['Content-Type'] = 'application/json'
req.body = JSON.dump(body)
end
req
end
def build_uri(endpoint, path, query)
origin = "https://#{@service_domain}.microcms.io"
path_with_id = path ? "/api/v1/#{endpoint}/#{path}" : "/api/v1/#{endpoint}"
encoded_query =
if !query || query.size.zero?
''
else
"?#{URI.encode_www_form(query)}"
end
URI.parse("#{origin}#{path_with_id}#{encoded_query}")
end
def build_http(uri)
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
http
end
end
# Client
class Client
include HttpUtil
def initialize(service_domain, api_key)
@service_domain = service_domain
@api_key = api_key
end
def list(endpoint, option = {})
list = send_http_request('GET', endpoint, nil, build_query(option))
if list[:totalCount]
list[:total_count] = list[:totalCount]
list.delete_field(:totalCount)
end
list
end
def get(endpoint, id = '', option = {})
send_http_request(
'GET',
endpoint,
id,
{
draftKey: option[:draft_key],
fields: option[:fields] ? option[:fields].join(',') : nil,
depth: option[:depth]
}.select { |_key, value| value }
)
end
def create(endpoint, content, option = {})
if content[:id]
put(endpoint, content, option)
else
post(endpoint, content, option)
end
end
def update(endpoint, content)
body = content.reject { |key, _value| key == :id }
send_http_request('PATCH', endpoint, content[:id], nil, body)
end
def delete(endpoint, id)
send_http_request('DELETE', endpoint, id)
end
private
# rubocop:disable Style/MethodLength
def build_query(option)
{
draftKey: option[:draftKey],
limit: option[:limit],
offset: option[:offset],
orders: option[:orders] ? option[:orders].join(',') : nil,
q: option[:q],
fields: option[:fields] ? option[:fields].join(',') : nil,
filters: option[:filters],
depth: option[:depth],
ids: option[:ids] ? option[:ids].join(',') : nil
}.select { |_key, value| value }
end
# rubocop:enable Style/MethodLength
def put(endpoint, content, option = {})
body = content.reject { |key, _value| key == :id }
send_http_request('PUT', endpoint, content[:id], option, body)
end
def post(endpoint, content, option = {})
send_http_request('POST', endpoint, nil, option, content)
end
end
# APIError
class APIError < StandardError
attr_accessor :status_code, :body
def initialize(status_code:, body:)
@status_code = status_code
@body = parse_body(body)
message = @body['message'] || 'Unknown error occurred.'
super(message)
end
def inspect
"#<#{self.class.name} @status_code=#{status_code}, @body=#{body.inspect} @message=#{message.inspect}>"
end
private
def parse_body(body)
JSON.parse(body)
rescue JSON::ParserError
{}
end
end
end