Class: Prismic::API

Inherits:
Object
  • Object
show all
Defined in:
lib/prismic/api.rb

Overview

The API is the main class

Defined Under Namespace

Classes: BadPrismicResponseError, OAuth, PrismicWSAuthError, PrismicWSConnectionError

Constant Summary

@@warned_create_search_form =
false
@@warned_oauth_initiate_url =
false
@@warned_oauth_check_token =
false

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(json, access_token, http_client, cache) {|_self| ... } ⇒ API

Returns a new instance of API

Yields:

  • (_self)

Yield Parameters:

  • _self (Prismic::API)

    the object that the method was called on

Raises:



37
38
39
40
41
42
43
44
45
# File 'lib/prismic/api.rb', line 37

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

Instance Attribute Details

#access_tokenString (readonly)

Returns:

  • (String)


11
12
13
# File 'lib/prismic/api.rb', line 11

def access_token
  @access_token
end

#bookmarksHash{String => String}

Returns list of bookmarks, as name -> documentId

Returns:

  • (Hash{String => String})

    list of bookmarks, as name -> documentId



16
17
18
# File 'lib/prismic/api.rb', line 16

def bookmarks
  @bookmarks
end

#cacheObject

Returns the value of attribute cache



19
20
21
# File 'lib/prismic/api.rb', line 19

def cache
  @cache
end

#experimentsExperiments

Returns list of all experiments from Prismic

Returns:

  • (Experiments)

    list of all experiments from Prismic



21
22
23
# File 'lib/prismic/api.rb', line 21

def experiments
  @experiments
end

#formsHash{String => Form}

Returns list of forms, as name -> Form

Returns:

  • (Hash{String => Form})

    list of forms, as name -> Form



18
19
20
# File 'lib/prismic/api.rb', line 18

def forms
  @forms
end

#http_clientObject (readonly)

Returns the value of attribute http_client



12
13
14
# File 'lib/prismic/api.rb', line 12

def http_client
  @http_client
end

#jsonObject (readonly)

Returns the value of attribute json



9
10
11
# File 'lib/prismic/api.rb', line 9

def json
  @json
end

#masterRef Also known as: master_ref

Returns the master reference

Returns:



34
35
36
# File 'lib/prismic/api.rb', line 34

def master
  @master
end

#oauthObject

Returns the value of attribute oauth



19
20
21
# File 'lib/prismic/api.rb', line 19

def oauth
  @oauth
end

#refsHash{String => Ref}

Returns list of references, as label -> reference

Returns:

  • (Hash{String => Ref})

    list of references, as label -> reference



14
15
16
# File 'lib/prismic/api.rb', line 14

def refs
  @refs
end

#tagsObject

Returns the value of attribute tags



19
20
21
# File 'lib/prismic/api.rb', line 19

def tags
  @tags
end

#typesObject

Returns the value of attribute types



19
20
21
# File 'lib/prismic/api.rb', line 19

def types
  @types
end

Class Method Details

.get(url, access_token = nil, http_client = Prismic::DefaultHTTPClient, api_cache = Prismic::DefaultCache) ⇒ Object

Fetch the API information from the Prismic.io server



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
# File 'lib/prismic/api.rb', line 164

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
    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

.oauth_check_token(url, oauth_params, api_opts = {}) ⇒ Object



242
243
244
245
246
247
248
249
250
251
# File 'lib/prismic/api.rb', line 242

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

.oauth_initiate_url(url, oauth_opts, api_opts = {}) ⇒ Object



222
223
224
225
226
227
228
229
230
231
# File 'lib/prismic/api.rb', line 222

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

.parse_api_response(data, access_token, http_client, cache) ⇒ Object



203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
# File 'lib/prismic/api.rb', line 203

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.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

.start(url, opts = {}) ⇒ Object



191
192
193
194
195
196
197
198
199
200
201
# File 'lib/prismic/api.rb', line 191

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.body)
  parse_api_response(json, access_token, http_client, cache)
end

Instance Method Details

#all(opts = {}) ⇒ Object

Retrieve all documents (paginated)

Parameters:

  • opts (Hash) (defaults to: {})

    query options (page, pageSize, ref, etc.)



96
97
98
99
# File 'lib/prismic/api.rb', line 96

def all(opts={})
  ref = opts['ref'] || opts[:ref] || self.master.ref
  form('everything', opts).submit(ref)
end

#as_jsonObject



159
160
161
# File 'lib/prismic/api.rb', line 159

def as_json
  @json
end

#bookmark(name) ⇒ String

Get a bookmark by its name

Parameters:

  • The (String)

    bookmark's name

Returns:

  • (String)

    The bookmark document id



52
53
54
# File 'lib/prismic/api.rb', line 52

def bookmark(name)
  bookmarks[name]
end

#create_search_form(name, data = {}, ref = {}) ⇒ Object

Deprecated.

Use #form instead.



78
79
80
81
82
83
84
# File 'lib/prismic/api.rb', line 78

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

#form(name, data = {}, ref = {}) ⇒ SearchForm

Returns a search form by its name. This is where you start to query a repository.

Parameters:

  • name (String)

    The name of the form

  • data (Hash) (defaults to: {})

    Default values

  • ref (type) (defaults to: {})

    Default reference

Returns:



72
73
74
75
# File 'lib/prismic/api.rb', line 72

def form(name, data={}, ref={})
  form = self.forms[name]
  form and form.create_search_form(data, ref)
end

#get_by_id(id, opts = {}) ⇒ Object Also known as: getByID

Retrieve one document by its id

Parameters:

  • id (String)

    the id to search

  • opts (Hash) (defaults to: {})

    query options (page, pageSize, ref, etc.)

Returns:

  • the document, or nil if not found



105
106
107
# File 'lib/prismic/api.rb', line 105

def get_by_id(id, opts={})
  query(Prismic::Predicates::at('document.id', id), opts)[0]
end

#get_by_ids(ids, opts = {}) ⇒ Object Also known as: getByIDs

Retrieve multiple documents by their ids

Parameters:

  • ids (String)

    the ids to fetch

  • opts (Hash) (defaults to: {})

    query options (page, pageSize, ref, etc.)

Returns:

  • the document, or nil if not found



124
125
126
# File 'lib/prismic/api.rb', line 124

def get_by_ids(ids, opts={})
  query(Prismic::Predicates::in('document.id', ids), opts)
end

#get_by_uid(typ, uid, opts = {}) ⇒ Object Also known as: getByUID

Retrieve one document by its uid

Parameters:

  • typ (String)

    the document type's name

  • uid (String)

    the uid to search

  • opts (Hash) (defaults to: {})

    query options (ref, etc.)

Returns:

  • the document, or nil if not found



115
116
117
# File 'lib/prismic/api.rb', line 115

def get_by_uid(typ, uid, opts={})
  query(Prismic::Predicates::at('my.'+typ+'.uid', uid), opts)[0]
end

#get_single(typ, opts = {}) ⇒ Object Also known as: getSingle

Retrieve one single typed document by its type

Parameters:

  • typ (String)

    the document type's name

  • opts (Hash) (defaults to: {})

    query options (ref, etc.)

Returns:

  • the document, or nil if not found



133
134
135
# File 'lib/prismic/api.rb', line 133

def get_single(typ, opts={})
  query(Prismic::Predicates::at('document.type', typ), opts)[0]
end

#has_cache?Boolean

Is the cache enabled on this API object?

Returns:

  • (Boolean)


26
27
28
# File 'lib/prismic/api.rb', line 26

def has_cache?
  !!cache
end

#oauth_check_token(params) ⇒ Object



253
254
255
256
257
258
259
260
# File 'lib/prismic/api.rb', line 253

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

#oauth_initiate_url(opts) ⇒ Object



233
234
235
236
237
238
239
240
# File 'lib/prismic/api.rb', line 233

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

#preview_session(token, link_resolver, default_url) ⇒ String

Return the URL to display a given preview (usually the home page of your site)

Parameters:

  • token (String)

    as received from Prismic server to identify the content to preview

  • link_resolver

    the link resolver to build URL for your site

  • default_url (String)

    the URL to default to return if the preview doesn't correspond to a document

Returns:

  • (String)

    the URL to redirect the user to



145
146
147
148
149
150
151
152
153
154
155
156
157
# File 'lib/prismic/api.rb', line 145

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'])).submit(token)
  if documents.results.size > 0
    link_resolver.link_to(documents.results[0])
  else
    default_url
  end
end

#query(q, opts = {}) ⇒ Object

Perform a query on this API. Use the master reference is no ref is specified in data.

Parameters:

  • q (String)

    the query to perform

  • opts (Hash) (defaults to: {})

    query options (page, pageSize, ref, etc.)



89
90
91
92
# File 'lib/prismic/api.rb', line 89

def query(q, opts={})
  ref = opts['ref'] || opts[:ref] || self.master.ref
  form('everything', opts).query(q).submit(ref)
end

#ref(name) ⇒ Ref

Get a reference by its alias

Parameters:

  • name (String)

    The reference's alias

Returns:

  • (Ref)

    The reference



61
62
63
# File 'lib/prismic/api.rb', line 61

def ref(name)
  refs[name.downcase]
end