-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathapp.js
121 lines (110 loc) · 3 KB
/
app.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
112
113
114
115
116
117
118
119
120
121
var express = require("express");
var http = require("http");
var qs = require("querystring");
var fdb = require('fdb').apiVersion(100);
var db;
//***********************************************
// Express configuration
//***********************************************
var app = express();
var httpServer = http.createServer(app);
app.configure(function() {
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.static(__dirname + '/public'));
});
//***********************************************
// FoundationDB configuration
//***********************************************
//fdb.options.setTraceEnable(".");
db = fdb.open(null, 'DB');
if (!db) {
console.log("SEVERE : Database connection problem.");
process.exit(1);
}
else {
console.log("Connected to database.");
}
//***********************************************
// Requests processing
//***********************************************
function findValues(req, resp) {
if (req.query.key) {
findByKey(req, resp);
}
else {
findByRange(req, resp);
}
}
function findByKey(req, resp) {
var key = req.query.key;
db.get(key, function(error, result) {
if (error) {
console.warn("ERROR : " + error);
resp.send(500);
}
else if (result) {
resp.send({ key : key, value : result.toString() });
}
else {
resp.send(404);
}
});
}
function findByRange(req, resp) {
var begin = req.query.begin;
var end = req.query.end;
db.getRange(begin, end, {}, function(error, results) {
if (error) {
console.warn("ERROR : " + error);
resp.send(500);
}
else if (results) {
var values = [];
results.forEach(function(result, index) {
values.push({ key : result.key.toString(),
value : result.value.toString() });
});
resp.send({ range : { begin : begin, end : end },
values : values });
}
else {
resp.send(404);
}
});
}
function insertValue(req, resp) {
var data = req.body;
db.set(data.key, data.value, function(error, result) {
if (error) {
console.warn("ERROR : " + error);
resp.send(500);
}
else {
resp.send(204);
}
});
}
function deleteValue(req, resp) {
var key = req.params.key;
db.clear(key, function(error, result) {
if (error) {
console.warn("ERROR : " + error);
resp.send(500);
}
else if (result) {
resp.send(204);
}
else {
resp.send(404);
}
});
}
//***********************************************
// REST API
//***********************************************
app.get("/fdb?", findValues);
app.post("/fdb", insertValue);
app.delete("/fdb/:key", deleteValue);
httpServer.listen(8888);
console.log("Listening on port 8888...");