-
Notifications
You must be signed in to change notification settings - Fork 3
/
app.js
90 lines (81 loc) · 3.32 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
var express = require('express')
, app = express()
, util = require('util')
, httpStatus = require('http-status')
, config = require(__dirname + '/config')
, Entry = require(__dirname + '/models/entry.js')
, INVALID_JSON_ERROR = 'Only valid JSON is supported via HTTP POST';
var entry = new Entry(config.mongodb.connectionUrl);
app.configure(function(){
app.use(express.bodyParser());
app.use(express.responseTime());
app.use(function(err, req, res, next){
res.send(INVALID_JSON_ERROR, httpStatus.UNSUPPORTED_MEDIA_TYPE);
});
});
app.post('/*', function(req, res){
if(req.is('application/json')) {
entry.save({body: req.body,
feed: req.params[0],
selfHref: config.server.domain + req.params[0]},
function(error, returnedEntry) {
if(error) {
res.send(error.message, httpStatus.INTERNAL_SERVER_ERROR);
} else {
res.send(returnedEntry, httpStatus.CREATED);
}
});
} else {
res.send(INVALID_JSON_ERROR, httpStatus.UNSUPPORTED_MEDIA_TYPE);
}
});
app.get('/*', function(req, res){
if(req.query.id != undefined) {
entry.getId(req.query.id, function (error, returnedEntry) {
if(error) {
res.send(error.message, httpStatus.BAD_REQUEST);
} else {
if(returnedEntry != undefined) {
res.json(returnedEntry);
} else {
res.send('The id specified was not found', httpStatus.NOT_FOUND);
}
}
});
} else {
var feedLimit = (req.query.limit == undefined) ? config.feed.limit : req.query.limit
, skip = (req.query.skip == undefined) ? config.feed.skip : req.query.skip;
entry.getFeed({ feed: req.params[0], limit: feedLimit, skip: skip }, function (error, returnedEntries) {
if(error) {
res.send(error.message, httpStatus.INTERNAL_SERVER_ERROR);
} else {
var entriesJSON = {}
, firstEntryID
, lastEntryID
, entryCount = 0;
for(var entry in returnedEntries){
if(entryCount === 0) {
firstEntryID = returnedEntries[entry].id;
}
// If there is only one entry the weak ETag should be the same unique id seperated by a dash
lastEntryID = returnedEntries[entry].id;
var tempJSONObj = {};
// TODO: This will "de-stringify" the body, there should be a better way to do this...
tempJSONObj.body = JSON.parse(returnedEntries[entry].body);
tempJSONObj.selfHref = returnedEntries[entry].selfHref;
tempJSONObj.entryDate = returnedEntries[entry].entryDate;
entriesJSON[returnedEntries[entry].id] = tempJSONObj;
entryCount++;
}
if(entryCount > 0) {
res.header('ETag', 'W/"' + firstEntryID + '-' + lastEntryID + '"');
res.json(entriesJSON);
} else {
res.send('The requested feed does not exist', httpStatus.NOT_FOUND);
}
}
});
}
});
app.listen(config.server.port);
console.log('Listening on port %d', config.server.port);