I'm have written an REST API in NodeJs Connect-rest and I was wondering how to go about storing the date and time the last call was made.
http://localhost:8080/api/books/metadata?id=12
module.exports.getItem = function(callback, id) {
var searchLetter = new RegExp(id, 'i');
//would like to record date/time the last time this call was made to this ID/row
//return the date/time back in the callback method
var row = items.filter(function(itemList) {
return searchLetter.test(itemList.asname);
});
return callback(null, {items: row, matches: row.length}, {headers: {'Content-type': 'application/json'}});
};
You can add a 'global route' to be used with any api call when your server is setup (that is, if you're using Express or restify or similar):
app.use(function (req, res, next) {
console.log( "Got a request at " + new Date() ); //might want to format date
});
(The request parameter might store the time already.)
Some of these frameworks will have an "after" event, that is fired after a request is completely handled (so this logging is not truely part of the chain). Like this example from restify, where I build a custom logging message:
server.on( 'after', function logRequest( req, res, route, error ) {
var latency = res.get( 'Response-Time' );
if ( typeof( latency ) !== 'number' )
latency = Date.now() - req._time;
var obj = {
userAgent: req.headers[ 'user-agent' ],
url: req.url,
method: req.method,
statusCode: res.statusCode,
req_id: req.getId()
};
obj.latency = latency;
server.log.info( obj );
} );
In this example I am using restify's logging middleware, but you could use your own logger, console.log, append to file, etc.