/
server.js
97 lines (84 loc) · 2.44 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
#! /usr/bin/env node
'use strict';
let application = require('koa')();
let qs = require('koa-qs');
let bodyParser = require('koa-bodyparser');
let route = require('koa-route');
let thunkify = require('thunkify');
let uuid = require('node-uuid');
let redis = require('redis');
let client = redis.createClient();
client.keys = thunkify(client.keys);
client.lrange = thunkify(client.lrange);
client.rpush = thunkify(client.rpush);
client.del = thunkify(client.del);
qs(application);
application.use(bodyParser());
application.use(require('koa-static')('public'));
application.use(route.get('/app', list));
application.use(route.get('/app/:id', get));
application.use(route.post('/app', add));
application.use(route.put('/app/:id', update));
application.use(route.del('/app/:id', del));
function *list () {
let apps = yield findAll();
this.set('X-Total-Count', apps.length);
this.body = apps.slice(this.query._start, this.query._end);
}
function * get (id) {
this.body = yield find(id);
}
function * add() {
this.body = yield create(this.request.body);
}
function * update (id) {
// remove old app
let old = yield find(id);
yield client.del(old.frontend);
this.body = yield create(this.request.body);
}
function * del (id) {
let app = yield find(id);
this.body = yield client.del(app.frontend);
}
// id, frontend, backends
function * findAll () {
let frontends = yield client.keys('frontend:*');
let apps = yield frontends.map(function (frontend) {
return client.lrange(frontend, 0, -1);
});
return frontends.map(function (frontend, index) {
return {
id: apps[index][0],
frontend: frontend,
backends: apps[index].slice(1),
};
});
}
// find app by identifier
function * find (id) {
let apps = yield findAll();
let app;
apps.some(function (item, index) {
if (item.id === id) {
app = item;
return true;
}
}, this);
return app;
}
function * create (app) {
let id = uuid.v4();
app.frontend = `frontend:${app.frontend}`;
app.backends = app.backends.split(',')
.map(function(s){return s.trim();})
.filter(function(s){return s;});
yield client.rpush(app.frontend, id);
yield app.backends.map(function (backend) {
return client.rpush(app.frontend, backend);
});
return yield find(id);
}
let port = 3000;
application.listen(port);
console.log(`Listen ${port}`);