-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
48 lines (36 loc) · 1.03 KB
/
index.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
const hypersource = require('hypersource')
const hyperclock = require('hyperclock')
const hypercore = require('hypercore')
const debug = require('debug')('clock.hypersource.club')
const ram = require('random-access-memory')
function createServer(opts) {
if (!opts || 'object' !== typeof opts) {
opts = {}
}
const server = hypersource.createServer(onrequest)
server.on('error', debug)
return server
function onrequest(req, res) {
res.interval = opts.interval
const source = hypercore(ram, req.key)
const clock = hyperclock(ram, res.key, res)
source.on('error', onerror)
clock.on('error', onerror)
req.on('error', onerror)
res.on('error', onerror)
source.replicate(req).once('handshake', onhandshake)
function onhandshake() {
clock.ready(() => {
clock.replicate(res).on('close', onclose).on('end', onclose)
})
}
function onclose() {
clock.close()
source.close()
}
function onerror(err) {
debug(err)
}
}
}
module.exports = createServer