pushd
Version:
Blazing fast multi-protocol mobile push notification service
87 lines (71 loc) • 2.95 kB
text/coffeescript
serial = 0
class Payload
locale_format: /^[a-z]{2}_[A-Z]{2}$/
constructor: (data) ->
throw new Error('Invalid payload') unless typeof data is 'object'
= serial++
= no
= {}
= {}
= {}
= {}
= yes
= {}
= false
# Read fields
for own key, value of data
if typeof key isnt 'string' or key.length == 0
throw new Error("Invalid field (empty)")
if typeof value isnt 'string'
throw new Error("Invalid value for `#{key}'")
switch key
when 'title' then .default = value
when 'msg' then .default = value
when 'sound' then = value
when 'incrementBadge' then = value != 'false'
when 'category' then = value
when 'contentAvailable' then = value != 'false'
else
if ([prefix, subkey] = key.split('.', 2)).length is 2
@[prefix][subkey] = value
else
throw new Error("Invalid field: #{key}")
# Detect empty payload
sum = 0
sum += (key for own key of @[type]).length for type in ['title', 'msg', 'data']
if sum is 0 then throw new Error('Empty payload')
localizedTitle: (lang) ->
localizedMessage: (lang) ->
localized: (type, lang) ->
unless
if @[type][lang]?
return @[type][lang]
# Try with lang only in case of full locale code (en_CA)
else if Payload::locale_format.test(lang) and @[type][lang[0..1]]?
return @[type][lang[0..1]]
else if @[type].default
return @[type].default
compile: ->
# Compile title and msg templates
@[type][lang] = for own lang, msg of @[type] for type in ['title', 'msg']
= yes
compileTemplate: (tmpl) ->
return tmpl.replace /\$\{(.*?)\}/g, (match, keyPath) =>
return @.variable(keyPath)
# Extracts variable from payload. The keyPath can be `var.somekey` or `data.somekey`
variable: (keyPath) ->
if keyPath is 'event.name'
# Special case
if ?.name
return ?.name
else
throw new Error("The ${#{keyPath}} does not exist")
[prefix, key] = keyPath.split('.', 2)
if prefix not in ['var', 'data']
throw new Error("Invalid variable type for ${#{keyPath}}")
if not @[prefix][key]?
throw new Error("The ${#{keyPath}} does not exist")
return @[prefix][key]
exports.Payload = Payload