在NodeJs中存储最后一次接收REST调用的日期/时间

Store date/time of last received REST call in NodeJs

本文关键字:调用 日期 时间 REST NodeJs 存储 最后一次      更新时间:2023-09-26

我已经在NodeJs Connect-rest中编写了一个REST API,我想知道如何存储最后一次调用的日期和时间。

这里是GET url调用

http://localhost:8080/api/books/metadata?id=12

过滤id

的代码片段
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'}});
};

你可以添加一个'global route',以便在你的服务器设置时(也就是说,如果你使用Express或restify或类似的)使用任何api调用:

app.use(function (req, res, next) {
    console.log( "Got a request at " + new Date() ); //might want to format date
});

(request参数可能已经存储了时间)

其中一些框架将有一个"after"事件,它在请求被完全处理后被触发(所以这个日志记录不是链的真正一部分)。就像这个来自restify的例子,我构建了一个自定义的日志消息:
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 );
} );

在这个例子中,我使用的是restify的日志中间件,但是你也可以使用你自己的日志记录器,console.log,追加到文件等