UNPKG

2.36 kBtext/coffeescriptView Raw
1superagent = require 'superagent'
2ServiceEnv = require './links/service-env'
3
4class 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 # TODO:
20 # This should probably use restify.JsonClient() or ganomede client lib,
21 # but let's just keep things simple for now.
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 # TODO:
32 # Should use bunyan instead of console.
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 # If process.env has variables with NOTIFICATIONS service address,
42 # returns Notification.send() bound to that address. Otherwise throws
43 # an error or returns noop depending on @noopIfNotFound argument.
44 #
45 # Example:
46 # sendNotification = Notification.sendFn()
47 # # now you can use `sendNotification(notification, callback)` in your code:
48 # sendNotification(new Notification(...))
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 # noop
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'] # These are filled in
69 # by notification service
70
71module.exports = Notification