-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
72 lines (53 loc) · 1.87 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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
var express = require('express');
var WebSocket = require('ws');
var http = require('http');
var q = require('q');
var r = require('rethinkdb');
var api = require('./api');
var cfgManager = require('node-config-manager');
var app = express();
var server = http.createServer(app);
var wss = new WebSocket.Server({ server });
var databaseSetUp = q.defer();
var connection;
var dbConfig;
/*============================================
= Load database config =
============================================*/
cfgManager.addConfig('db');
dbConfig = cfgManager.getConfig('db');
/*===========================================
= Setup DB connection =
===========================================*/
r.connect({ host: 'localhost', port: 28015 }, function(err, conn) {
if (err) throw err;
connection = conn;
r.dbList().contains(dbConfig.name)
.do(function(databaseExists) {
return r.branch(databaseExists, { dbs_created: 0 }, r.dbCreate(dbConfig.name));
})
.do(function() {
return r.db(dbConfig.name).tableList().contains('posts').do(function(tableExists) {
return r.branch(tableExists, { tables_created: 0 }, r.db(dbConfig.name).tableCreate('posts'));
})
})
.run(conn, function(err, cursor) {
if (err) throw err;
conn.use(dbConfig.name);
databaseSetUp.resolve(connection);
});
});
/*======================================
= Startup server =
======================================*/
databaseSetUp.promise.then(function() {
app.use('/api', api(databaseSetUp.promise, wss));
wss.on('connection', function connection(ws, req) {
ws.on('message', function incoming(message) {
console.log('received: %s', message);
});
});
server.listen(3000, function listening() {
console.log('Listening on %d', server.address().port);
});
})