Sha256: d75c46568dc1d2f510be658e4f932279d61e711d50ff6b94edf914d012a2fe5b

Contents?: true

Size: 1.04 KB

Versions: 3

Compression:

Stored size: 1.04 KB

Contents

class BMC::FCM::Request
  extend AttrExtras.mixin

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

  class << self
    attr_writer :api_key

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

  attr_reader_initialize :request_body

  attr_reader :response_json

  def self.call(...)
    new(...).call
  end

  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

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

  def error?
    !ok?
  end

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

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

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
bmc-1.1.0 app/libs/bmc/fcm/request.rb
bmc-1.0.1 app/libs/bmc/fcm/request.rb
bmc-1.0.0 app/libs/bmc/fcm/request.rb