Class: Firebase::Admin::Messaging::MessageEncoder

Inherits:
Object
  • Object
show all
Includes:
Utils
Defined in:
lib/firebase/admin/messaging/message_encoder.rb

Instance Method Summary collapse

Methods included from Utils

#check_analytics_label, #check_color, #check_numeric, #check_numeric_array, #check_string, #check_string_array, #check_string_hash, #check_time, #to_seconds_string

Instance Method Details

#encode(message) ⇒ String

Parameters:

  • message (Message)

    The message to encode.

Returns:

  • (String)

    A json encoded string.

Raises:



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/firebase/admin/messaging/message_encoder.rb', line 12

def encode(message)
  raise ArgumentError, "message must be a Message" unless message.is_a?(Message)
  result = {
    android: encode_android(message.android),
    apns: encode_apns(message.apns),
    condition: check_string("Message.condition", message.condition, non_empty: true),
    data: check_string_hash("Message.data", message.data),
    notification: encode_notification(message.notification),
    token: check_string("Message.token", message.token, non_empty: true),
    topic: check_string("Message.topic", message.topic, non_empty: true),
    fcmOptions: encode_fcm_options(message.fcm_options)
  }
  result[:topic] = sanitize_topic_name(result[:topic])
  result = remove_nil_values(result)
  unless result.count { |k, _| [:token, :topic, :condition].include?(k) } == 1
    raise ArgumentError, "Exactly one token, topic or condition must be specified"
  end
  result
end

#sanitize_topic_name(topic, strip_prefix: true) ⇒ String?

Returns:

  • (String, nil)


33
34
35
36
37
38
39
40
41
42
43
# File 'lib/firebase/admin/messaging/message_encoder.rb', line 33

def sanitize_topic_name(topic, strip_prefix: true)
  return nil unless topic
  prefix = "/topics/"
  if topic.start_with?(prefix)
    topic = topic[prefix.length..]
  end
  unless /\A[a-zA-Z0-9\-_.~%]+\Z/.match?(topic)
    raise ArgumentError, "Malformed topic name."
  end
  strip_prefix ? topic : "/topics/#{topic}"
end