forked from purifycss/purify-app
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
111 lines (85 loc) · 2.3 KB
/
server.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
//Require hook to compile all subsequent .js files to es6
require("./register-babel");
// Used to proxy webpack bundles from webpack - dev - server to localhost
var serve = require('koa-static');
var router = require('koa-router')();
var proxy = require('koa-proxy');
var bundle = require('./server/webpack.bundle');
var co = require('co');
var logger = require('koa-logger');
var config = require('./config/rethink.js');
var r = require('rethinkdbdash')(config.rethinkdb);
var koa = require('koa');
var app = module.exports = koa();
var port = process.env.PORT || 3000;
var env = process.env.NODE_ENV || 'dev';
/*
ROUTING
*/
app.use(logger());
// serve static index.html
app.use(serve(__dirname));
//mount router
app.use(router.routes());
router.get('/test', function*() {
this.body = "Hello, World";
});
//start webpack bundling process
bundle();
//route localhost:3000 request to localhost:8080 to fetch
//latest bundle
router.all('/build/*', proxy({
url: 'http://localhost:8090/build/bundle.js'
}));
/*
RETHINKDB
*/
//Initialize database
co(function*() {
try {
console.log('Initializing database...');
var name = 'purify';
yield r.dbCreate(name).run();
console.log('Database `purify` created');
yield r.db(name).tableCreate("urls").run();
console.log('Table `urls` created');
yield r.db(name).table("urls")
.indexCreate("url").run();
console.log('Database created on port 8080');
} catch (err) {
if (err.message.indexOf("already exists") !== -1)
console.log(err.message);
}
});
router.get('/api/get', get);
router.post('/api/update', update);
function* get(next) {
try {
this.body =
yield r.db("purify").table("urls").run();
} catch (err) {
this.status = 500;
this.body = err.message || http.STATUS_CODES[this.status];
}
yield next;
}
function* update(next) {
try {
// Parse the POST data
var url =
yield parse(this);
// Insert a new Todo
this.body = yield r.db("purify").table('urls').insert({'url':url}).run();
console.log('succesfully inserted');
} catch (err) {
this.status = 500;
this.body = err.message || http.STATUS_CODES[this.status];
}
yield next;
}
/*
OPEN KOA CONNECTION
*/
var server = app.listen(port, function() {
console.log('Listening on port %d', server.address().port);
});