1 | superagent = require 'superagent'
|
2 | ServiceEnv = require './links/service-env'
|
3 |
|
4 | class Notification
|
5 | constructor: (options={}) ->
|
6 | for key in Notification.REQUIRED_KEYS
|
7 | unless options.hasOwnProperty(key)
|
8 | throw new Error "Required key missing: `#{key}`"
|
9 |
|
10 | @[key] = options[key]
|
11 |
|
12 | for key in Notification.OPTIONAL_KEYS
|
13 | keyAllowed = options.hasOwnProperty(key) &&
|
14 | (-1 == Notification.SERVERSIDE_KEYS.indexOf(key))
|
15 |
|
16 | if keyAllowed
|
17 | @[key] = options[key]
|
18 |
|
19 |
|
20 |
|
21 |
|
22 | @send: (uri, notification, callback) ->
|
23 | unless notification.hasOwnProperty('secret')
|
24 | notification.secret = process.env.API_SECRET
|
25 |
|
26 | superagent
|
27 | .post(uri)
|
28 | .send(notification)
|
29 | .end (err, res) ->
|
30 | if (err)
|
31 |
|
32 |
|
33 | console.error "Notification.send() failed:",
|
34 | err: err
|
35 | uri: uri
|
36 | notification: notification
|
37 | response: if res then res.body else undefined
|
38 |
|
39 | callback?(err, res?.body)
|
40 |
|
41 |
|
42 |
|
43 |
|
44 |
|
45 |
|
46 |
|
47 |
|
48 |
|
49 |
|
50 | @sendFn: (noopIfNotFound) ->
|
51 | unless ServiceEnv.exists('NOTIFICATIONS', 8080)
|
52 | unless noopIfNotFound
|
53 | throw new Error("Notification.sendFn() failed to
|
54 | find NOTIFICATIONS service address in environment variables")
|
55 |
|
56 |
|
57 | return () ->
|
58 | callback = arguments[arguments.length - 1]
|
59 | callback?(null)
|
60 |
|
61 | baseURL = ServiceEnv.url('NOTIFICATIONS', 8080)
|
62 | url = "#{baseURL}/notifications/v1/messages"
|
63 | return (notification, callback) ->
|
64 | Notification.send(url, notification, callback)
|
65 |
|
66 | @REQUIRED_KEYS: ['from', 'to', 'type']
|
67 | @OPTIONAL_KEYS: ['data', 'secret']
|
68 | @SERVERSIDE_KEYS: ['id', 'timestamp']
|
69 |
|
70 |
|
71 | module.exports = Notification
|