快速中间件缓存

Express middleware caching

我正在尝试使用 express 中间件实现一些缓存,这似乎工作得很好,但我在某个地方陷入了无限循环。

在我的路由器中,我必须遵循以下路线:

router.get('/test', [middleware.cache.cache('1 day', true), controllers.test]);

middleware.cache.cache 看起来像这样:

module.exports.cache = function(time, global) {
    // Do some stuff with the time here

    return function cache(req, res, next) {
        // Keep a copy of the actual send method
        res._send = res.send;

        // Overwrite the res.send function
        res.send = function(obj) {
             console.log('[' + res.statusCode + '] Cache: ' + redisKey);

             // Get the key from redis
             redis.get(redisKey)
                .then(function(result) {
                    result = JSON.parse(result);

                    if(!_.isNull(result)) {
                        console.log('Expired cache found');

                        // Send initial object
                        return res._send(obj);
                    } else {
                        console.log('Cache found');

                        // Send back cached object
                        return res._send(result.obj);
                    }
                } else {
                    console.log('No data found');

                    storeInRedis(redisKey, obj, time);

                    // Send initial object
                    return res._send(obj);
                }
            })
            .fail(function(err) {
                console.log(err);

                return res._send(obj);
            });
        };

        next();
    };
};

我得到的输出如下所示:

[200] Cache: cache_global_test
Cache found
[200] Cache: cache_global_test
Cache found
...

所以我怀疑当我调用res._send(obj)时,它实际上指的是我刚刚覆盖的原始res.send。这当然会导致无限循环。 但我真的找不到任何解决方案。

res._send = res.send 不创建副本。

它创建对您稍后要更改的函数的引用。

要创建副本,请使用:https://www.npmjs.com/package/clone

为什么你需要 'Overwrite the res.send function' res.send 功能?

你可以在redis.get(redisKey).then里面使用next()来实现你想要的。

我认为像这样更改 send 可能是一件危险的事情,因为它是一个内置的 express 方法,而您的 'last function' 和其他开发人员希望它表现出express 文档中描述的方式。

最好使用缓存中间件将 isCachedcache 属性添加到 res,然后在 'last function' 中进行相应操作,使其明确意识到可能存在缓存值和缓存中间件。