Class: HeyYouFcmPush::Connection

Inherits:
Object
  • Object
show all
Includes:
Singleton
Defined in:
lib/hey_you_fcm_push/connection.rb

Defined Under Namespace

Classes: AuthError, ResponseError

Constant Summary collapse

URL_TMPL =
"https://fcm.googleapis.com/v1/projects/%{project_id}/messages:send".freeze
AUTH_SCOPES =
['https://www.googleapis.com/auth/firebase.messaging'].freeze
RETRY_COUNT =
1
HTTP_CODES =
{
  not_auth: 401,
  server_error: 500
}

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeConnection

Returns a new instance of Connection.



18
19
20
21
22
23
24
25
# File 'lib/hey_you_fcm_push/connection.rb', line 18

def initialize
  @authorization = Google::Auth.get_application_default(AUTH_SCOPES)
  @options = { headers: { 'Content-Type': 'application/json' } }
  @project_id = HeyYou::Config::FcmPush.instance.project_id
  @uri = URL_TMPL % { project_id: project_id }

  reauth
end

Instance Attribute Details

#authorizationObject (readonly)

Returns the value of attribute authorization.



16
17
18
# File 'lib/hey_you_fcm_push/connection.rb', line 16

def authorization
  @authorization
end

#optionsObject (readonly)

Returns the value of attribute options.



16
17
18
# File 'lib/hey_you_fcm_push/connection.rb', line 16

def options
  @options
end

#project_idObject (readonly)

Returns the value of attribute project_id.



16
17
18
# File 'lib/hey_you_fcm_push/connection.rb', line 16

def project_id
  @project_id
end

#uriObject (readonly)

Returns the value of attribute uri.



16
17
18
# File 'lib/hey_you_fcm_push/connection.rb', line 16

def uri
  @uri
end

Instance Method Details

#reauthObject



40
41
42
# File 'lib/hey_you_fcm_push/connection.rb', line 40

def reauth
  authorization.apply!(options[:headers])
end

#send_notification(message, validate_only: false, retry_count: 0) ⇒ Object



27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/hey_you_fcm_push/connection.rb', line 27

def send_notification(message, validate_only: false, retry_count: 0)
  request_options = options.clone
  request_options[:body] = { message: message, validate_only: validate_only }.to_json

  make_request(request_options)
rescue AuthError => e
  retry_count += 1
  raise e if retry_count > RETRY_COUNT

  reauth
  return send_notification(message, validate_only: validate_only, retry_count: retry_count + 1)
end