Class: Agilibox::FCM::Request

Inherits:
Service
  • Object
show all
Defined in:
app/libs/agilibox/fcm/request.rb

Constant Summary collapse

URL =
"https://fcm.googleapis.com/fcm/send"

Class Attribute Summary collapse

Instance Attribute Summary collapse

Instance Method Summary collapse

Class Attribute Details

.api_keyObject



7
8
9
# File 'app/libs/agilibox/fcm/request.rb', line 7

def api_key
  @api_key ||= ENV["FCM_API_KEY"]
end

Instance Attribute Details

#response_jsonObject (readonly)

Returns the value of attribute response_json.



14
15
16
# File 'app/libs/agilibox/fcm/request.rb', line 14

def response_json
  @response_json
end

Instance Method Details

#callObject



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'app/libs/agilibox/fcm/request.rb', line 16

def call
  response_body = HTTParty.post(URL,
    :body    => request_body.to_json,
    :headers => {
      "Content-Type"  => "application/json",
      "Authorization" => "key=#{self.class.api_key}",
    },
  ).body

  @response_json = JSON.parse(response_body).deep_symbolize_keys

  self
rescue JSON::ParserError
  @response_json = {success: 0, failure: 1, results: [{:error => "InvalidJsonResponse"}]}
  self
end

#error?Boolean

Returns:

  • (Boolean)


37
38
39
# File 'app/libs/agilibox/fcm/request.rb', line 37

def error?
  !ok?
end

#errorsObject



41
42
43
# File 'app/libs/agilibox/fcm/request.rb', line 41

def errors
  response_json[:results].pluck(:error).compact
end

#invalid_token?Boolean

Returns:

  • (Boolean)


45
46
47
# File 'app/libs/agilibox/fcm/request.rb', line 45

def invalid_token?
  errors.include?("NotRegistered") || errors.include?("InvalidRegistration")
end

#ok?Boolean

Returns:

  • (Boolean)


33
34
35
# File 'app/libs/agilibox/fcm/request.rb', line 33

def ok?
  response_json[:success].positive? && response_json[:failure].zero?
end