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