1 | _ = require 'lodash'
|
2 | http = require 'http'
|
3 |
|
4 | class PublishMessage
|
5 | constructor: (options={}) ->
|
6 | {
|
7 | @firehoseClient
|
8 | @uuidAliasResolver
|
9 | } = options
|
10 |
|
11 | _doCallback: (request, code, callback) =>
|
12 | response =
|
13 | metadata:
|
14 | responseId: request.metadata.responseId
|
15 | code: code
|
16 | status: http.STATUS_CODES[code]
|
17 | callback null, response
|
18 |
|
19 | do: (request, callback) =>
|
20 | {fromUuid, toUuid, route} = request.metadata
|
21 | lastHop = _.last route
|
22 | return @_doCallback request, 422, callback unless fromUuid?
|
23 | return @_doCallback request, 422, callback unless toUuid?
|
24 | return @_doCallback request, 422, callback unless lastHop?
|
25 | return @_doCallback request, 204, callback unless lastHop.from == lastHop.to && lastHop.type == 'message.received'
|
26 |
|
27 | @uuidAliasResolver.resolve toUuid, (error, toUuid) =>
|
28 | return callback error if error?
|
29 | return @_doCallback request, 204, callback unless lastHop.to == toUuid
|
30 |
|
31 | message = JSON.stringify @_buildMessage request
|
32 | @_send {toUuid, message}, (error) =>
|
33 | return callback error if error?
|
34 | return @_doCallback request, 204, callback
|
35 |
|
36 | _buildMessage: (request) =>
|
37 | return {
|
38 | metadata:
|
39 | responseId: request.metadata.responseId
|
40 | route: request.metadata.route
|
41 | forwardedRoutes: request.metadata.forwardedRoutes
|
42 | rawData: request.rawData
|
43 | }
|
44 |
|
45 | _send: ({toUuid, message}, callback=->) =>
|
46 | @firehoseClient.publish toUuid, message, callback
|
47 |
|
48 | module.exports = PublishMessage
|