-
Notifications
You must be signed in to change notification settings - Fork 4
/
index.coffee
81 lines (61 loc) · 2.42 KB
/
index.coffee
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
fs = require 'fs'
http = require 'http'
stream = require 'stream'
express = require 'express'
WServer = require('ws').Server
app = express()
# -----------------------------------------------------------------------------
app.configure ->
app.set 'views', "#{__dirname}/views"
app.set 'view engine', 'html'
app.engine 'html', (file, options, callback) ->
fs.readFile file, (err, file) -> callback err, file.toString()
app.use app.router
app.use express.static "#{__dirname}/public"
app.use express.errorHandler dumpExceptions: true, showStack: true
app.get '/', (req, res) ->
res.render 'index'
# -----------------------------------------------------------------------------
log = (args...) -> console.log '[LevelDB] ' + args.join(' ')
class GUI
constructor: (db) ->
@use db
use: (db) =>
@level = db
return this
WSSetup: (@ws) =>
log "Client connected"
@send = (message) => @ws.send JSON.stringify message
ws.on 'message', @socketAPI
socketAPI: (data) =>
return unless try data = JSON.parse data
{ method, args } = data
log "#{method} [#{args}]"
if method is 'get'
args.push (error, results) => @send { error, results }
@level[method].apply @level, args
if method is 'put'
message = "It went okay"
args.push (error, results) => @send { error, message, key: args[0], value: args[1] }
@level[method].apply @level, args
if method is 'del'
message = "Key '#{args[0]}' removed."
args.push (error, results) => @send { error, message }
@level[method].apply @level, args
if method in ['createReadStream', 'createKeyStream', 'createValueStream']
options = args[0] || {}
options.limit ?= 100
s = @level[method](options)
s.on 'data', (data) =>
switch method
when 'createKeyStream' then data = { key: data, value: '' }
when 'createValueStream' then data = { key: '', value: data }
@send data
s.on 'error', (error) => @send { error }
listen: (port = 4420) =>
server = http.createServer(app)
server.listen port
wss = new WServer { server }
wss.on 'connection', @WSSetup
log "Server listening on port #{port}"
module.exports = GUI