This repository has been archived by the owner on Jul 4, 2019. It is now read-only.
forked from eiriklv/collectify
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwebsocket-api.js
119 lines (106 loc) · 2.36 KB
/
websocket-api.js
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
'use strict';
/**
* Dependencies
*/
const http = require('http');
const debug = require('debug')('collectify:websocket-api');
const highland = require('highland');
const lodash = require('lodash-fp');
const EventEmitter = require('events').EventEmitter;
const websocket = require('websocket-stream');
const { Receiver, Transmitter } = require('interprocess-push-stream');
/**
* Application-specific modules
*/
const config = require('./config');
const inspect = require('./helpers/inspect').bind(null, debug);
/**
* Create streams for the channels
* on which we want to
* distribute / emit data.
*
* This uses the push-version
* of the interface, but you
* could also use the pull-version,
* to enable load balancing
* and back-pressure between
* processes
*/
const updatesChannel = Receiver({
channel: 'entries:updated',
prefix: config.get('database.redis.prefix'),
url: config.get('database.redis.url')
});
/**
* Create a new event-emitter
* which we are going to use
* for errors
*
* We'll also make a curryed
* version of eventEmitter.emit
* that we'll use in our
* application
*/
const eventEmitter = new EventEmitter();
const emit = lodash.curryN(2, eventEmitter.emit.bind(eventEmitter));
/**
* Create a stream
* where we'll
* collect all the
* errors emitted
* throughout the
* the stream pipeline(s)
*/
const errorStream = highland('error', eventEmitter);
/**
* Create a stream
* with the newChannel
* as the source
*/
const updatesStream = highland(updatesChannel)
.compact()
.flatten()
.errors(emit('error'))
/**
* Log all the updated
* articles and the
* resulting entries in
* mongodb
*/
updatesStream
.fork()
.doto(inspect('top-stories-update'))
.resume()
/**
* Pipe all errors
* to the error channel
*/
errorStream
.doto(inspect('error-stream'))
.resume()
/**
* Create an http server
* which we'll use to
* attach a websocket server
*/
const httpServer = http.createServer()
/**
* Create a websocket server
* where we 'plug' our content
* stream into the websocket(s)
*
* (We also kill the stream when the client ends)
*/
const wss = websocket.createServer({
server: httpServer
}, (stream) => {
let contentStream = updatesStream
.observe()
.map(JSON.stringify)
.doto(highland.log)
contentStream.pipe(stream)
stream.once('close', () => {
contentStream.destroy();
});
});
server.listen(3333);