Class: Istox::SnsPublisher

Inherits:
Object
  • Object
show all
Defined in:
lib/istox/helpers/sns_publisher.rb

Class Method Summary collapse

Class Method Details

.publish(message, topic_arn: nil, throw_exception: false) ⇒ Object

exception will not be thrown if throw_exception is set to false, exception will only be printed out and swallowed



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/istox/helpers/sns_publisher.rb', line 7

def publish(message, topic_arn: nil, throw_exception: false)
  if message.nil?
    log.info('No message to publish, skipping SNS publish now...')
    return
  end

  log.info('Publishing to SNS...')

  message = JSON.generate(message) unless message.is_a? String

  topic = topic_arn || ENV.fetch('SNS_CLIENT_TOPIC', '')

  log.info("Publishing SNS to topic: #{topic} with message: #{message}")

  sns_client.publish(topic_arn: topic, message: message)

  log.info('Publish to SNS successfully.')
rescue StandardError => e
  log.info 'Unable to publish SNS message.'
  log.info(e)
  log.info('Failed to publish SNS, ignoring...') unless throw_exception

  raise e if throw_exception
end

.sns_clientObject



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/istox/helpers/sns_publisher.rb', line 32

def sns_client
  return @sns_client if @sns_client.present?

  access_key = ENV.fetch('AWS_STS_ACCESS_KEY_ID', nil)

  if access_key.present?
    credentials = Aws::Credentials.new(ENV.fetch('AWS_STS_ACCESS_KEY_ID', nil), ENV.fetch('AWS_STS_SECRET_ACCESS_KEY', nil))
    Aws.config.update(region: ENV.fetch('AWS_REGION', 'ap-southeast-1'),
                      credentials: credentials)
  else
    Aws.config.update(region: ENV.fetch('AWS_REGION', 'ap-southeast-1'))
  end

  @sns_client = Aws::SNS::Client.new(region: ENV.fetch('AWS_REGION', 'ap-southeast-1'))
end