Class: Databox::Client

Inherits:
Object
  • Object
show all
Includes:
HTTParty
Defined in:
lib/databox/client.rb

Direct Known Subclasses

Integration

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeClient

Returns a new instance of Client.



19
20
21
22
23
24
# File 'lib/databox/client.rb', line 19

def initialize
  Databox.configure unless Databox.configured?

  self.class.base_uri url
  self.class.basic_auth key, "password"
end

Instance Attribute Details

#tokenObject

Returns the value of attribute token.



11
12
13
# File 'lib/databox/client.rb', line 11

def token
  @token
end

Instance Method Details

#handle(response) ⇒ Object



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/databox/client.rb', line 37

def handle response
  if response.code > 201
    raise Databox::ClientError.new(
      response.code.to_s+" - "+
      response.parsed_response["error"]["type"]+" - "+
      response.parsed_response["error"]["message"]
    )
  end

  output = response.parsed_response

  if output.is_a?(Hash) and output.keys.include?("response")
    Databox::Response.new(output["response"])
  elsif output.is_a?(Array)
    output.map { |item| Databox::Response.new(item) }
  else
    output
  end
end

#keyObject



16
# File 'lib/databox/client.rb', line 16

def key; Databox.configuration.key end

#logsObject



33
34
35
# File 'lib/databox/client.rb', line 33

def logs
  handle self.class.get("/push/custom/#{self.token}/logs")
end

#push(data = {}) ⇒ Object



26
27
28
29
30
31
# File 'lib/databox/client.rb', line 26

def push data={}
  if validate data
    data = [data] unless data.is_a?(Array)
    handle self.class.post("/push/custom/#{self.token}", body: { data: data }.to_json)
  end
end

#urlObject



17
# File 'lib/databox/client.rb', line 17

def url; Databox.configuration.url end

#validate(data) ⇒ Object



57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
# File 'lib/databox/client.rb', line 57

def validate data
  return data.map do |dp|
    validate(dp)
  end if data.is_a?(Array)

  errors = []
  errors.push("Data is missing") if data.nil? or data == {}
  errors.push("Key is required") if data[:key].nil?
  # errors.push("Value is required") if data[:value].nil?

  errors.push("Date format is invalid") if not(data[:date].nil?) and (Date.iso8601(data[:date]) rescue false) == false
  errors.push("Key format is invalid") unless data[:key] =~/^[a-zA-Z0-9_\.\@]*$/

  unless errors.empty?
    invalid_record = Databox::InvalidRecord.new "Payload is invalid"
    invalid_record.errors = errors
    raise invalid_record
  end

  true
end