1 | crema = require "crema"
|
2 | MessageBuilder = require("./message").Builder
|
3 | pushPlugin = require "./push/plugin"
|
4 | pullPlugin = require "./pull/plugin"
|
5 | collectPlugin = require "./collect/plugin"
|
6 | plugins = require "./plugins"
|
7 | disposable = require "disposable"
|
8 | _ = require "underscore"
|
9 |
|
10 |
|
11 | class Router
|
12 |
|
13 | |
14 |
|
15 |
|
16 | constructor: () ->
|
17 |
|
18 |
|
19 | @directors = {}
|
20 |
|
21 |
|
22 |
|
23 | @parse = crema
|
24 |
|
25 | @_messageBuilder = new MessageBuilder @
|
26 |
|
27 |
|
28 | @_plugins = new plugins @
|
29 |
|
30 |
|
31 |
|
32 | @use pushPlugin
|
33 |
|
34 |
|
35 | @use pullPlugin
|
36 |
|
37 |
|
38 | @use collectPlugin
|
39 |
|
40 | |
41 |
|
42 |
|
43 |
|
44 |
|
45 | use: (plugin) -> @_plugins.add plugin
|
46 |
|
47 | |
48 |
|
49 |
|
50 | using: () -> @_plugins.using()
|
51 |
|
52 |
|
53 | |
54 |
|
55 |
|
56 |
|
57 | on: (routeOrListeners, ops, callback) ->
|
58 |
|
59 | if typeof ops == 'function'
|
60 | callback = ops
|
61 | ops = {}
|
62 |
|
63 |
|
64 | listenerDisposables = disposable.create()
|
65 |
|
66 |
|
67 |
|
68 | if typeof routeOrListeners == "object" and not callback
|
69 | for type of routeOrListeners
|
70 | listenerDisposables.add @.on(type, routeOrListeners[type])
|
71 | return listenerDisposables
|
72 |
|
73 |
|
74 | if typeof routeOrListeners == "string"
|
75 | routes = crema routeOrListeners
|
76 | else if routeOrListeners instanceof Array
|
77 | routes = routeOrListeners
|
78 | else
|
79 | routes = [routeOrListeners]
|
80 |
|
81 | for route in routes
|
82 | do (route) =>
|
83 |
|
84 | route.type = ops.type if ops.type
|
85 | _.extend route.tags, ops.tags if ops.tags
|
86 |
|
87 | listenerDisposables.add @director(route.type).addListener(route, callback)
|
88 |
|
89 |
|
90 | @_plugins.newListener route: route, callback: callback
|
91 |
|
92 |
|
93 |
|
94 | listenerDisposables
|
95 |
|
96 | |
97 |
|
98 |
|
99 |
|
100 | director: (type) ->
|
101 | director = @directors[type]
|
102 | throw new Error "director #{type} does not exist" if not director
|
103 | return director
|
104 |
|
105 | |
106 |
|
107 |
|
108 | channels: (ops) ->
|
109 |
|
110 | channels = []
|
111 |
|
112 | for name of @directors
|
113 | director = @directors[name]
|
114 | channels = channels.concat director.channels ops
|
115 |
|
116 | return channels
|
117 |
|
118 |
|
119 | dispatch: (messageWriter) -> @director(messageWriter.type).dispatch(messageWriter)
|
120 |
|
121 | |
122 |
|
123 |
|
124 |
|
125 | req: () -> @request.apply this, arguments
|
126 |
|
127 | |
128 |
|
129 |
|
130 |
|
131 | request: (channel, query, headers) ->
|
132 |
|
133 | @_messageBuilder.
|
134 | clean().
|
135 | channel(if typeof channel is "string" then crema.parseChannel(channel) else channel).
|
136 | query(query).
|
137 | headers(headers);
|
138 |
|
139 |
|
140 |
|
141 |
|
142 |
|
143 | module.exports = Router |
\ | No newline at end of file |