gpt4 book ai didi

javascript - 如何在 ember 数据中缓存查询结果

转载 作者:IT王子 更新时间:2023-10-29 03:12:50 26 4
gpt4 key购买 nike

我想在 ember-data 中缓存查询结果。 (查找查询)

明确一点:我不想缓存整个模型;只有什么模型是查询的结果。正确的位置在哪里?

我正在考虑在适配器中实现它并缓存 AJAX 调用的结果,但我认为这不是一个好的解决方案,因为我不想覆盖加载的、可能是更新的和/或修改的模型数据.

我认为只返回一个 ID 列表是不可能的,并且操作适配器这个简单用例的序列化程序似乎很困惑!

实际上我不希望为特定类型的查询调用findQuery。类似于 findAll 的行为。不错的东西类似于 queryShouldBeCached Hook 。

有好的解决方案吗?

最佳答案

我不是 Ember 专家,但我认为您可以使用纯 JS 解决方案来解决您的问题。

给定的 Ember 数据查询返回 promise ,例如return this.store.findAll('blog-post');//=> Promise,我们可以在具有高阶函数(返回函数的函数)的简单对象中缓存 promises。对象缓存可以替换为 localStoragesessionStorageMap 甚至 WeakMap 但我正在使用对象缓存使事情变得简单易懂。

您基本上要做的是替换以下调用:

return this.store.findAll('blog-post');

或多或少像:

return cachedStore.findAll('blog-post');

实际上,使用下面的解决方案可能看起来更像:

return cachedStore.call(this, 'findAll', 'blog-post');

因此,您将请求一次数据,并在后续调用中始终从缓存中返回。

让我向您展示实现的样子:

var cachedStore = (function () {
// Your cache - in this case simple object literal
var cache = {};

// Actual method that will check cache for results before trying to query services
return function (method) {
var args = Array.prototype.slice.call(arguments, 1);
var serializedArgs = JSON.stringify(args);

if (!(serializedArgs in cache)) {
cache[serializedArgs] = this.store[method].apply(this, args);
}
return cache[serializedArgs];
};
}());

这是一个示例用法:

// Fires a request
cachedStore.call(this, 'findAll', 'blog-post');
// Returns from cache
cachedStore.call(this, 'findAll', 'blog-post');
// Returns from cache
cachedStore.call(this, 'findAll', 'blog-post');

// Fires a request
cachedStore.call(this, 'findRecord', 'blog-post', 123);
// Returns from cache
cachedStore.call(this, 'findRecord', 'blog-post', 123);
// Returns from cache
cachedStore.call(this, 'findRecord', 'blog-post', 123);

这有什么帮助吗?

关于javascript - 如何在 ember 数据中缓存查询结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30009059/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com