1 | class SocketIORemoteEndpoint
|
2 |
|
3 | initialize: (options = {}, callback = ->) ->
|
4 | @_processOptions options
|
5 |
|
6 | @_io.sockets.on 'connection', (socket) =>
|
7 | socket.on 'RPC_Request', (rpcRequest) =>
|
8 | @_handleRpcRequestEvent rpcRequest, socket
|
9 |
|
10 |
|
11 | socket.on 'JoinRoom', (roomName) =>
|
12 | @_rpcRequestMiddleware roomName, socket
|
13 | .then =>
|
14 | socket.join roomName
|
15 | .catch (error) ->
|
16 |
|
17 |
|
18 |
|
19 | socket.on 'LeaveRoom', (roomName) ->
|
20 | socket.leave roomName
|
21 |
|
22 | callback()
|
23 |
|
24 |
|
25 | setRPCHandler: (@_handleRPCRequest) ->
|
26 |
|
27 |
|
28 | _processOptions: (options) ->
|
29 | if options.ioInstance
|
30 | @_io = options.ioInstance
|
31 | else
|
32 |
|
33 | @_io = require('socket.io')()
|
34 | @_io.listen 3000
|
35 |
|
36 | if options.rpcRequestMiddleware
|
37 | @_rpcRequestMiddleware = options.rpcRequestMiddleware
|
38 | else
|
39 | @_rpcRequestMiddleware = ->
|
40 | then: (callback) ->
|
41 | callback()
|
42 | catch: ->
|
43 |
|
44 |
|
45 | _handleRpcRequestEvent: (rpcRequest, socket) ->
|
46 | emitRpcResponse = (error, response) =>
|
47 | rpcId = rpcRequest.rpcId
|
48 | socket.emit 'RPC_Response',
|
49 | rpcId: rpcId
|
50 | err: error
|
51 | data: response
|
52 |
|
53 | @_rpcRequestMiddleware rpcRequest, socket
|
54 | .then =>
|
55 | @_handleRPCRequest rpcRequest, emitRpcResponse
|
56 | .catch (error) ->
|
57 | emitRpcResponse error, null
|
58 |
|
59 |
|
60 | publish: (context, [domainEventName, aggregateId]..., payload) ->
|
61 | fullEventName = @_getFullEventName context, domainEventName, aggregateId
|
62 | @_io.to(fullEventName).emit fullEventName, payload
|
63 |
|
64 |
|
65 | _getFullEventName: (context, domainEventName, aggregateId) ->
|
66 | fullEventName = context
|
67 | if domainEventName
|
68 | fullEventName += "/#{domainEventName}"
|
69 | if aggregateId
|
70 | fullEventName += "/#{aggregateId}"
|
71 | fullEventName
|
72 |
|
73 |
|
74 | close: ->
|
75 | @_io.close()
|
76 |
|
77 |
|
78 | module.exports = new SocketIORemoteEndpoint |
\ | No newline at end of file |