-
Notifications
You must be signed in to change notification settings - Fork 77
/
api.js
47 lines (41 loc) · 1.31 KB
/
api.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
var mongo = require('mongodb').MongoClient,
fiddles = null;
module.exports = function(app) {
mongo.connect(String(process.env.MONGOHQ_URL), function(err, db) {
fiddles = db.collection('fiddles');
});
app.get(/^\/fiddles\/\w+$/, function(req, res) {
var fiddle = req.url.split('/').pop();
if (fiddle) {
fiddles.findOne({fiddle: fiddle}, function(err, item) {
if (item) {
res.json(item);
} else {
res.json({
'message': 'No fiddle found.'
});
}
});
}
});
app.post('/save', function(req, res) {
var now = Date.now(),
fiddle = parseInt(now, 10).toString(36);
if (req.body.value) { //don't save anything empty
fiddles.findOne({fiddle: fiddle}, function(err, item) {
if (!item) {
fiddles.insert({
fiddle: fiddle,
value: req.body.value
}, function() {
console.log('Inserted fiddle at', fiddle + '.');
});
}
});
}
res.json({
saved: true,
fiddle: fiddle
});
});
};