Class: Craigslist::API::Envelope

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

Overview

The response wrapper every JSON Bulkpost endpoint returns.

{"apiVersion": 1, "data": {...}, "errors": [], "accountMessages": []}

Note that errors can be populated on an HTTP 200 — status alone is not enough to tell whether a call worked.

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(api_version: nil, data: nil, errors: [], account_messages: []) ⇒ Envelope

Returns a new instance of Envelope.



27
28
29
30
31
32
33
# File 'lib/craigslist/api/envelope.rb', line 27

def initialize(api_version: nil, data: nil, errors: [], account_messages: [])
  @api_version = api_version
  @data = data
  @errors = Array(errors)
  @account_messages = Array()
  freeze
end

Instance Attribute Details

#account_messagesArray<Hash> (readonly)

Returns {"messageId", "message"} notices, which keep appearing until acknowledged via Resources::Account#acknowledge.

Returns:



25
26
27
# File 'lib/craigslist/api/envelope.rb', line 25

def 
  @account_messages
end

#api_versionNumeric? (readonly)

Returns:

  • (Numeric, nil)


15
16
17
# File 'lib/craigslist/api/envelope.rb', line 15

def api_version
  @api_version
end

#dataHash, ... (readonly)

Returns the useful payload.

Returns:

  • (Hash, Array, nil)

    the useful payload



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

def data
  @data
end

#errorsArray<Hash> (readonly)

Returns {"code", "message"} entries.

Returns:

  • (Array<Hash>)

    {"code", "message"} entries



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

def errors
  @errors
end

Class Method Details

.parse(body) ⇒ Envelope

Parameters:

  • body (String)

    raw JSON response body

Returns:

Raises:



38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/craigslist/api/envelope.rb', line 38

def self.parse(body)
  payload = JSON.parse(body.to_s)

  # A few error paths return a bare object rather than a full envelope.
  payload = {} unless payload.is_a?(Hash)

  new(
    api_version: payload["apiVersion"],
    data: payload["data"],
    errors: payload["errors"],
    account_messages: payload["accountMessages"]
  )
rescue JSON::ParserError => e
  raise ParseError, "expected JSON from the Bulkpost API: #{e.message}"
end

Instance Method Details

#error?Boolean

Returns:

  • (Boolean)


55
56
57
# File 'lib/craigslist/api/envelope.rb', line 55

def error?
  !errors.empty?
end

#error_messageString

Returns errors joined into one human-readable line.

Returns:

  • (String)

    errors joined into one human-readable line



60
61
62
# File 'lib/craigslist/api/envelope.rb', line 60

def error_message
  errors.map { |e| e["message"] }.compact.join("; ")
end