-
Notifications
You must be signed in to change notification settings - Fork 35
/
api.rb
332 lines (300 loc) · 10.9 KB
/
api.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
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
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
# encoding: utf-8
module Prismic
# The API is the main class
class API
@@warned_create_search_form = false
@@warned_oauth_initiate_url = false
@@warned_oauth_check_token = false
attr_reader :json
# @return [String]
attr_reader :access_token
attr_reader :http_client
# @return [Hash{String => Ref}] list of references, as label -> reference
attr_accessor :refs
# @return [Hash{String => String}] list of bookmarks, as name -> documentId
attr_accessor :bookmarks
# @return [Hash{String => Form}] list of forms, as name -> Form
attr_accessor :forms
attr_accessor :tags, :types, :oauth, :cache
# @return [Experiments] list of all experiments from Prismic
attr_accessor :experiments
# Is the cache enabled on this API object?
#
# @return [Boolean]
def has_cache?
!!cache
end
# Returns the master {Ref reference}
# @api
#
# @return [Ref] The master {Ref reference}
attr_accessor :master
alias :master_ref :master
def initialize(json, access_token, http_client, cache)
@json = json
@access_token = access_token
@http_client = http_client
yield self if block_given?
@cache = cache
self.master = refs.values && refs.values.map { |ref| ref if ref.master? }.compact.first
raise BadPrismicResponseError, 'No master Ref found' unless master
end
# Get a bookmark by its name
# @api
# @param [String] The bookmark's name
#
# @return [String] The bookmark document id
def bookmark(name)
bookmarks[name]
end
# Get a {Ref reference} by its alias
# @api
# @param name [String] The reference's alias
#
# @return [Ref] The reference
def ref(name)
refs[name.downcase]
end
# Returns a {Prismic::SearchForm search form} by its name. This is where you start to query a repository.
# @api
# @param name [String] The name of the form
# @param data [Hash] Default values
# @param ref [type] Default {Ref reference}
#
# @return [SearchForm] The search form
def form(name, data={}, ref={})
form = self.forms[name]
form and form.create_search_form(data, ref)
end
# @deprecated Use {#form} instead.
def create_search_form(name, data={}, ref={})
unless @@warned_create_search_form
warn '[DEPRECATION] `create_search_form` is deprecated. Please use `form` instead.'
@@warned_create_search_form = true
end
form(name, data, ref)
end
# Perform a query on this API. Use the master reference is no ref is specified in data.
# @param q [String] the query to perform
# @param opts [Hash] query options (page, pageSize, ref, etc.)
def query(q, opts={})
ref = opts['ref'] || opts[:ref] || self.master.ref
form('everything', opts).query(q).submit(ref)
end
# Retrieve all documents (paginated)
# @param opts [Hash] query options (page, pageSize, ref, etc.)
def all(opts={})
ref = opts['ref'] || opts[:ref] || self.master.ref
form('everything', opts).submit(ref)
end
# Retrieve one document by its id
# @param id [String] the id to search
# @param opts [Hash] query options (page, pageSize, ref, etc.)
# @return the document, or nil if not found
def get_by_id(id, opts={})
unless opts.key?("lang")
opts["lang"] = '*'
end
query(Prismic::Predicates::at('document.id', id), opts)[0]
end
alias :getByID :get_by_id
# Retrieve one document by its uid
# @param typ [String] the document type's name
# @param uid [String] the uid to search
# @param opts [Hash] query options (ref, etc.)
# @return the document, or nil if not found
def get_by_uid(typ, uid, opts={})
unless opts.key?("lang")
opts["lang"] = '*'
end
query(Prismic::Predicates::at('my.'+typ+'.uid', uid), opts)[0]
end
alias :getByUID :get_by_uid
# Retrieve multiple documents by their ids
# @param ids [String] the ids to fetch
# @param opts [Hash] query options (page, pageSize, ref, etc.)
# @return the document, or nil if not found
def get_by_ids(ids, opts={})
unless opts.key?("lang")
opts["lang"] = '*'
end
query(Prismic::Predicates::in('document.id', ids), opts)
end
alias :getByIDs :get_by_ids
# Retrieve multiple documents by their uids
# @param typ [String] the document type's name
# @param uids [String] the uids to search
# @param opts [Hash] query options (ref, etc.)
def get_by_uids(typ, uids, opts = {})
unless opts.key?("lang")
opts["lang"] = '*'
end
query(Prismic::Predicates::in('my.'+typ+'.uid', uids), opts)
end
alias :getByUIDs :get_by_uids
# Retrieve one single typed document by its type
# @param typ [String] the document type's name
# @param opts [Hash] query options (ref, etc.)
# @return the document, or nil if not found
def get_single(typ, opts={})
query(Prismic::Predicates::at('document.type', typ), opts)[0]
end
alias :getSingle :get_single
# Return the URL to display a given preview
# @param token [String] as received from Prismic server to identify the content to preview
# @param link_resolver the link resolver to build URL for your site
# @param default_url [String] the URL to default to return if the preview doesn't correspond to a document
# (usually the home page of your site)
#
# @return [String] the URL to redirect the user to
def preview_session(token, link_resolver, default_url)
response = self.http_client.get(token, {}, 'Accept' => 'application/json')
if response.code.to_s != '200'
return default_url
end
json = JSON.load(response.body)
documents = self.form('everything').query(Prismic::Predicates.at('document.id', json['mainDocument'])).lang("*").submit(token)
if documents.results.size > 0
link_resolver.link_to(documents.results[0])
else
default_url
end
end
def as_json
@json
end
# Fetch the API information from the Prismic.io server
def self.get(url, access_token=nil, http_client=Prismic::DefaultHTTPClient, api_cache=Prismic::DefaultCache)
data = {}
data['access_token'] = access_token if access_token
cache_key = url + (access_token ? ('#' + access_token) : '')
api_cache.get_or_set(cache_key, nil, 5) {
res = http_client.get(url, data, 'Accept' => 'application/json')
case res.code
when '200'
res.body
when '401', '403'
begin
json = JSON.load(res.body)
raise PrismicWSAuthError.new(
json['error'],
json['oauth_initiate'],
json['oauth_token'],
http_client
)
rescue => e
raise PrismicWSConnectionError.new(res, e)
end
else
raise PrismicWSConnectionError, res
end
}
end
def self.start(url, opts={})
http_client = opts[:http_client] || Prismic::DefaultHTTPClient
access_token = opts[:access_token]
# We don't use ||= because we want to keep the DefaultCache if nil was explicitly passed
api_cache = opts.has_key?(:api_cache) ? opts[:api_cache] : Prismic::DefaultCache
cache = opts.has_key?(:cache) ? opts[:cache] : Prismic::DefaultCache
resp = get(url, access_token, http_client, api_cache)
json = JSON.load(resp)
parse_api_response(json, access_token, http_client, cache)
end
def self.parse_api_response(data, access_token, http_client, cache)
data_forms = data['forms'] || []
data_refs = data.fetch('refs'){ raise BadPrismicResponseError, "No refs given" }
new(data, access_token, http_client, cache) {|api|
api.bookmarks = data['bookmarks']
api.forms = Hash[data_forms.map { |k, form|
[k, Form.from_json(api, form)]
}]
api.refs = Hash[data_refs.map { |ref|
scheduled_at = ref['scheduledAt']
[(ref['label']&.downcase || ref['id']), Ref.new(ref['id'], ref['ref'], ref['label'], ref['isMasterRef'], scheduled_at && Time.at(scheduled_at / 1000.0))]
}]
api.tags = data['tags']
api.types = data['types']
api.oauth = OAuth.new(data['oauth_initiate'], data['oauth_token'], http_client)
api.experiments = Experiments.parse(data['experiments'])
}
end
def self.oauth_initiate_url(url, oauth_opts, api_opts={})
oauth =
begin
api = self.start(url, api_opts)
api.oauth
rescue PrismicWSAuthError => e
e.oauth
end
oauth.initiate_url(oauth_opts)
end
def oauth_initiate_url(opts)
if !@@warned_oauth_initiate_url
warn "[DEPRECATION] Method `API#oauth_initiate_url` is deprecated. " +
"Please use `Prismic::API.oauth_initiate_url` instead."
@@warned_oauth_initiate_url = true
end
oauth.initiate_url(opts)
end
def self.oauth_check_token(url, oauth_params, api_opts={})
oauth =
begin
api = self.start(url, api_opts)
api.oauth
rescue PrismicWSAuthError => e
e.oauth
end
oauth.check_token(oauth_params)
end
def oauth_check_token(params)
unless @@warned_oauth_check_token
warn "[DEPRECATION] Method `API#oauth_check_token` is deprecated. " +
"Please use `Prismic::API.oauth_check_token` instead."
@@warned_oauth_check_token = true
end
oauth.check_token(params)
end
private
class BadPrismicResponseError < Error ; end
class PrismicWSConnectionError < Error
def initialize(resp, cause=nil)
super("Can't connect to Prismic's API: #{resp.code} #{resp.message}", cause)
end
end
class PrismicWSAuthError < Error
attr_reader :error, :oauth
def initialize(error, oauth_initialize, oauth_token, http_client)
super("Can't connect to Prismic's API: #{error}")
@error = error
@oauth = OAuth.new(oauth_initialize, oauth_token, http_client)
end
end
class OAuth
attr_reader :initiate, :token, :http_client
def initialize(initiate, token, http_client)
@http_client = http_client
@initiate = initiate
@token = token
end
def initiate_url(opts)
initiate + '?' + {
'client_id' => opts.fetch(:client_id),
'redirect_uri' => opts.fetch(:redirect_uri),
'scope' => opts.fetch(:scope),
}.map{|kv| kv.map{|e| CGI.escape(e) }.join('=') }.join('&')
end
def check_token(params)
res = http_client.post(token, params)
if res.code == '200'
begin
JSON.load(res.body)['access_token']
rescue Exception => e
raise PrismicWSConnectionError.new(res, e)
end
else
raise PrismicWSConnectionError, res
end
end
end
end
end