Return sequelize 挂钩的不同结果

Return different results from a sequelize hook

我正在尝试整理我的缓存是如何工作的,因此想将它实现到我的模型的钩子中。这是我到目前为止所实施的,我可以看到它正在正确设置和获取缓存。

hooks: {
        beforeFind: function(opts,fn) {
            cache.get(this.getTableName() + ':' + opts.where.id, function(err, result) {
                if (result) {
                    return fn(null, result);
                }

                return fn(null, opts);
            });
        },
        afterFind: function(result, options, fn) {
            cache.set(this.getTableName() + ':' + result.getDataValue('id'), result, function () {
                return fn(null, result);
            });
        },
}

问题是,缓存命中后,它仍在执行数据库查询并return从数据库中获取结果。

有人可以告诉我如何 return 从缓存中获取结果并且在缓存命中的情况下不执行数据库查询吗?

让我们看一下代码findAll (because it is calling for all finds). You can see, that it will return Promise, where first executes hooks and in then block there is you query. That's why you can't implement cache in such way. There is a hot discussion in this issue sequelize 需要如何实现插件系统(尤其是缓存)。

你能知道什么?看看这个 lib,其中 Cacher 对象是通过模型实现的。