-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathServer.js
More file actions
614 lines (559 loc) · 16.8 KB
/
Copy pathServer.js
File metadata and controls
614 lines (559 loc) · 16.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
'use strict';
/*
* Router Receives a connection String
*
* it will perform the conneciton to the server. Anytime the connection si closed
* it will try to reconnect. Until it fails several times.
*
*/
var WebSocketRouter = function WebSocketRouter(connection, ctx) {
//
var BEFORE = 'BEFORE';
//
var AFTER = 'AFTER;';
/*
* @name Close
*
* Closes the connection and clears all data related to the object
*
* @function
* @return {None}
*
*/
Router.prototype.close = function () {
this.messageQueue = [];
if (this.connection.readyState == 1) {
this.connection.close();
} else {
this.connection.onopen = function () {
this.connection.close();
};
}
};
/*
* @name Router
*
* Implements a routifier which lets you define URL to your handlers
* The URLs will respond to methods and chainable, meaning that a chai
* of responsability (by the given order) will be respected.
* If one of the handlers, fails, it will break the chain.
* Optionally, actions (in a similar fashion to REST) can be defined,
* also filters.
* You can attach hooks to your url handlers which will let you prepare your
* data or scenario before executing a particular task or set of tasks
*
* @constructor
* @param {String} connection_query
* Defines the FQDM to connect to (eg: ws(s)://localhost:8080)
* @param {*} ctx
* Defines the root context to which all the Handlers will be attached by
* default, if no other handler is specified
* @return {Router}
*
*/
function Router(connection, ctx) {
if (connection.on) {
connection.on('message', function (message) {
return dispatch(JSON.parse(message));
});
connection.on('close', function (data) {
for (var i = 0; i < events.length; i++) {
if (events[i].n == 'close') events[i].fn(data);
}
});
} else {
connection.onmessage = function (message) {
return dispatch(JSON.parse(message.data));
};
connection.onclose = function (data) {
for (var i = 0; i < events.length; i++) {
if (events[i].n == 'close') events[i].fn(data);
}
};
}
this.action = {
UPDATE: 'UPDATE',
DELETE: 'DELETE',
CREATE: 'CREATE',
SUBSCRIBE: 'SUBSCRIBE',
REQUEST: 'REQUEST'
//Due to several version of the router beeing used on different places of the application
};this.version = '1.3.2';
//
this.events = [];
//
this.lastEvents = [];
//
this.registeredTasks = [];
// Will manage all connection-related aspects
// Of the WebSocket
this.connection = connection;
}
/*
* @name Send
*
* Executes the current message, and the BEFORE and AFTER hooks
*
* @function
* @param {Object} message
* Object message to be sent to the server
* @return {None}
*
*/
Router.prototype.send = function (message) {
try {
this.executeTaks(message, BEFORE);
this.connection.send(JSON.stringify(message));
this.executeTaks(message, AFTER);
} catch (err) {
console.log(err);
}
};
/*
* @name Exception Handler
*
* Receives an error and returns a message ready to be
* delivered to the client.
*
* @function
* @param {Error} error
* Object message to be sent to the server
* @return {None}
*
*/
Router.prototype.ExceptionHandler = function (error) {
return {
'message': error.stack
};
};
/*
* @name On
*
* Receives a route and a callback and returns a builder object
* that will let you define, chainable, action, filters, bind and executeLast,
* properties.
*
* action - receives a constante (or value) and filter also by defined
* action in the server.
*
* filters - receives an object and filter also by key-values defined in the
* filters, and also present in the received message.
*
* bind - Receives any object and binds the callback to the specified context.
*
* executeLast - will push this callback to the end of the event queue, beeing
* making it the last in the chain of responsability.
*
* @function
* @param {String} name
* Route to match
* @param {Function} callback
* Callback to execute whenever the criterias ar meet
* @return {{
* action: {Function} (action),
* filters: {Function} (object),
* bind: {Function} (context),
* executeLast: {Function} ()
* }}
*
*/
Router.prototype.on = function (n, fn) {
var event = { n: this.routify(n), fn: fn, action: "*" };
this.events.push(event);
return new function () {
this.action = function (ACTION) {
if (ACTION) event.action = ACTION;
return this;
};
this.filters = function (filters) {
if (filters) event.filters = filters;
return this;
};
this.bind = function (bind) {
if (bind) event.bind = bind;
return this;
};
this.executeLast = function () {
lastEvents.push(events[events.indexOf(event)]);
delete events[events.indexOf(event)];
events.length = events.length - 1;
};
}();
};
/*
* @name Delete
*
* Receives a route, a callback and filters, creates a new listener for
* those criterias and the DELETE action
*
* @function
* @param {String} name
* Route to match
* @param {Function} callback
* Callback to execute whenever the criterias ar meet
* @param {Object} filters
* Object used to match parameters in the body and filter messages.
* @return {{
* action: {Function} (action),
* filters: {Function} (object),
* bind: {Function} (context),
* executeLast: {Function} ()
* }}
*
*/
Router.prototype.delete = function (n, fn, filters) {
return this.on(n, fn).action(this.action.DELETE).filters(filters);
};
/*
* @name Update
*
* Receives a route, a callback and filters, creates a new listener for
* those criterias and the UPDATE action
*
* @function
* @param {String} name
* Route to match
* @param {Function} callback
* Callback to execute whenever the criterias ar meet
* @param {Object} filters
* Object used to match parameters in the body and filter messages.
* @return {{
* action: {Function} (action),
* filters: {Function} (object),
* bind: {Function} (context),
* executeLast: {Function} ()
* }}
*
*/
Router.prototype.update = function (n, fn, filters) {
return this.on(n, fn).action(this.action.UPDATE).filters(filters);
};
/*
* @name Create
*
* Receives a route, a callback and filters, creates a new listener for
* those criterias and the CREATE action
*
* @function
* @param {String} name
* Route to match
* @param {Function} callback
* Callback to execute whenever the criterias ar meet
* @param {Object} filters
* Object used to match parameters in the body and filter messages.
* @return {{
* action: {Function} (action),
* filters: {Function} (object),
* bind: {Function} (context),
* executeLast: {Function} ()
* }}
*
*/
Router.prototype.create = function (n, fn, filters) {
return this.on(n, fn).action(this.action.CREATE).filters(filters);
};
/*
* @name Request
*
* Receives a route, a callback and filters, creates a new listener for
* those criterias and the REQUEST action
*
* @function
* @param {String} name
* Route to match
* @param {Function} callback
* Callback to execute whenever the criterias ar meet
* @param {Object} filters
* Object used to match parameters in the body and filter messages.
* @return {{
* action: {Function} (action),
* filters: {Function} (object),
* bind: {Function} (context),
* executeLast: {Function} ()
* }}
*
*/
Router.prototype.request = function (n, fn, filters) {
return this.on(n, fn).action(this.action.REQUEST).filters(filters);
};
/*
* @name Subscribe
*
* Receives a route, a callback and filters, creates a new listener for
* those criterias and the SUBSCRIBE action
*
* @function
* @param {String} name
* Route to match
* @param {Function} callback
* Callback to execute whenever the criterias ar meet
* @param {Object} filters
* Object used to match parameters in the body and filter messages.
* @return {{
* action: {Function} (action),
* filters: {Function} (object),
* bind: {Function} (context),
* executeLast: {Function} ()
* }}
*
*/
Router.prototype.subscribe = function (n, fn, filters) {
return this.on(n, fn).action(this.action.SUBSCRIBE).filters(filters);
};
/*
* @name Intercept
*
* Mirros send function. Create for more client legibility and code
* Maintanability
*
* @function
* @param {String} name
* Route to match
* @param {Function} callback
* Callback to execute whenever the criterias ar meet
* @return {{
* action: {Function} (action),
* filters: {Function} (object),
* bind: {Function} (context),
* executeLast: {Function} ()
* }}
*
*/
Router.prototype.intercept = function (n, fn) {
this.events.push({ n: this.routify(n), fn: fn });
};
/*
* @name Before Send
*
* Attachs a before send hook to a particular route.
*
* @function
* @param {String} name
* Route to match
* @param {Function} callback
* Callback to execute whenever the criterias ar meet
* @return {None}
*
*/
Router.prototype.beforeSend = function (route, fn) {
this.registerSendTask(route, fn, BEFORE);
};
/*
* @name After Send
*
* Attachs a after send hook to a particular route.
*
* @function
* @param {String} name
* Route to match
* @param {Function} callback
* Callback to execute whenever the criterias ar meet
* @return {None}
*
*/
Router.prototype.afterSend = function (route, fn) {
this.registerSendTask(route, fn, AFTER);
};
/*
* @name Register Send Task
*
* Attachs a hook, by the defined criterias. (Not intended for public use yet)
*
*/
Router.prototype.registerSendTask = function (route, fn, position) {
this.registeredTasks.push({
route: this.routify(route),
fn: fn,
position: position
});
};
/*
* @name Message
*
* Sends a message to the server. The default route is * which can be
* Overriten. All parameters are optional.
*
* @function
* @param {{
* route: {String},
* action: {String},
* data: {Object}
* }} options
* @return {None}
*
*/
Router.prototype.message = function (options) {
this.send(Object.assign({ route: "*" }, options));
};
/*
* @name Apply Filters
*
* Checks if an object meets the filters criteria (Not intended for public use)
*
* @function
* @param {Object} target_filters
* @param {Object} destiny_filters
* @return {Boolean}
*
*/
Router.prototype.applyFilters = function (dataFilters, eventFilters) {
var isFilterMatching = true;
Object.keys(eventFilters).forEach(key => {
if (!this.routify(dataFilters[key].toString ()).exec(eventFilters[key].toString ())) {
isFilterMatching = false;
}
});
return isFilterMatching;
}
/*
* @name Should Event Execute
*
* Checks if a event should execute or not (Not intended for public use)
*
* @function
* @param {Object} data
* @param {Object} evt
* @return {Boolean}
*
*/
Router.prototype.shouldEventExecute = function (data, evt) {
if (!this.routify (evt.action).exec(data.action)) {
return false;
}
if ((evt.filters && !data.data) || (data.data && evt.filters && !this.applyFilters(data.data, evt.filters))) {
return false;
}
return evt.n.exec(data.route);
}
/*
* @name Should Task Execute
*
* Checks if a task should execute or not (Not intended for public use)
*
* @function
* @param {Object} data
* @param {Object} task
* @param {String} position
* @return {Boolean}
*
*/
Router.prototype.shouldTaskExecute = function (data, task, position) {
if (position != task.position) {
return false;
}
return task.route.exec(data.route);
};
/*
* @name Apply To Queue
*
* Adds the current event to the execution queue (Not intended for public use)
*
* @function
* @param {Object} event
* @param {Array} run
* @return {None}
*
*/
Router.prototype.applyToQueue = function (evt, run) {
if (evt.fn instanceof Array) {
for (var j = 0; j < evt.fn.length; j++) {
run.push(evt.fn[j].bind(evt.bind ? evt.bind : ctx));
}
} else {
run.push(evt.fn.bind(evt.bind ? evt.bind : ctx));
}
};
/*
* @name Dispatch
*
* Dispatchs the current event and the associated hooks (Not intended for public use)
*
* @function
* @param {Object} data
* @return {None}
*
*/
Router.prototype.dispatch = function (data) {
var run = [];
//Events
for (var i = 0; i < this.events.length; i++) {
if (this.shouldEventExecute(data, this.events[i])) {
this.applyToQueue(this.events[i], run);
}
}
//Execute Last Events
for (var i = 0; i < this.lastEvents.length; i++) {
if (this.shouldEventExecute(data, this.lastEvents[i])) {
this.applyToQueue(this.lastEvents[i], run);
}
}
this.runner(run, data.data);
};
/*
* @name Runner
*
* Runs the provided callbacks array (Not intended for public use)
*
* @function
* @param {Array} run
* @param {Object} data
* @return {None}
*
*/
Router.prototype.runner = function (run, data) {
try {
for (var i = 0; i < run.length; i++) {
run[i](data);
}
} catch (e) {
this.error(this.ExceptionHandler(e));
}
};
/*
* @name Routify
*
* Turns a Route String into a regex (Not intended for public use)
*
* @function
* @param {String} route
* @return {Regex}
*
*/
Router.prototype.routify = function (n) {
return new RegExp('^' + n.replace(/\*/g, '[^\/]+').replace(/\//g, '\\/') + '$', '');
};
/*
* @name Error
*
* Sends an error whenever the server or the client
* has failed (Not intended for public use)
*
* @function
* @param {Error} error
* @return {None}
*
*/
Router.prototype.error = function (error) {
this.send({ route: '/socket/error', data: error });
};
/*
* @name Execute Tasks
*
* Executes all the tasks by a hook identifier (Not intended for public use)
*
* @function
* @param {Object} data
* @param {String} position
* @return {None}
*
*/
Router.prototype.executeTaks = function (data, position) {
for (var i = 0; i < this.registeredTasks.length; i++) {
if (this.shouldTaskExecute(data, this.registeredTasks[i], position)) {
this.registeredTasks[i].fn.bind(ctx)(data);
}
}
};
return new Router(connection, ctx);
};
if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') module.exports = WebSocketRouter;