Skip to content

Commit 94aa4ff

Browse files
authored
Merge pull request martinyung#1 from martinyung/feature/object-model
Feature/object model
2 parents c8bc1af + 91c532c commit 94aa4ff

File tree

3 files changed

+68
-0
lines changed

3 files changed

+68
-0
lines changed

app.js

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,4 +3,7 @@ var express = require('express');
33
var app = express();
44
var db = require('./db');
55

6+
var ItemController = require('./item/ItemController');
7+
app.use('/items', ItemController);
8+
69
module.exports = app;

item/Item.js

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
var mongoose = require('mongoose');
2+
var ItemSchema = new mongoose.Schema({
3+
key: String,
4+
value: String,
5+
timestamp: {
6+
type: Number,
7+
default: Math.floor(Date.now() / 1000)
8+
}
9+
});
10+
11+
mongoose.model('Item', ItemSchema);
12+
module.exports = mongoose.model('Item');

item/ItemController.js

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
var express = require('express');
2+
var router = express.Router();
3+
var bodyParser = require('body-parser');
4+
router.use(bodyParser.urlencoded({ extended: true }));
5+
6+
var Item = require('./Item');
7+
module.exports = router;
8+
9+
// Create an item or update existing item
10+
router.post('/', (req, res) => {
11+
var query = { 'key': req.body.key };
12+
var update = {
13+
value: req.body.value,
14+
timestamp: Math.floor(Date.now() / 1000)
15+
};
16+
var options = {
17+
upsert: true,
18+
new: true
19+
}
20+
Item.findOneAndUpdate(query, update, options, (err, item) => {
21+
if (err) return res.status(500).send('error');
22+
res.status(200).send(item);
23+
});
24+
});
25+
26+
// Get the value according to key
27+
router.get('/:key', (req, res) => {
28+
var timestampQuery = parseInt(req.query.timestamp)
29+
// Get the value less than or equal to the timestamp in query string
30+
if (timestampQuery) {
31+
Item.find({
32+
'key': req.params.key,
33+
'timestamp': { $lte : timestampQuery }
34+
}).
35+
sort({ 'timestamp': -1 }).
36+
limit(1).
37+
exec((err, item) => {
38+
if (err) return res.status(500).send('error');
39+
if (item.length === 0) return res.status(404).send('not found');
40+
res.status(200).send('value: ' + item[0].value)
41+
});
42+
}
43+
// Get the latest value accroding to key when no timestamp query string is given
44+
else {
45+
Item.find({ 'key': req.params.key }).
46+
sort({ 'timestamp': -1 }).
47+
exec((err, item) => {
48+
if (err) return res.status(500).send('error');
49+
if (item.length === 0) return res.status(404).send('not found');
50+
res.status(200).send('value: ' + item[0].value);
51+
});
52+
}
53+
});

0 commit comments

Comments
 (0)