如何在remix.run dev模式下使用内存中缓存?
我需要从非常缓慢且很少更改的API中获取数据,因此我认为我会使用内存缓存。我首先尝试了一种非常简单的方法,只需将其保存到我路线上的加载器函数范围之外的变量:
let cache;
export const loader = async () => {
if (!cache) {
// we always end up here
cache = await (await fetch("...)).json()
}
}
但这是不起作用的。然后,我尝试了一个适当的缓存库(lru-cache
),但是该缓存也总是空的。然后,我意识到,我猜是一个dev模式的每个请求中重新加载了entired文件,因此我尝试将缓存的创建移至单独的文件 cache.server.ts 并从那里。
import LRU from "lru-cache";
console.log("Creating cache"); // this is logged on each request
const cache = new LRU({ max: 200 });
export default cache;
但是该文件似乎也在每个请求上重新加载。
如果我构建生产版本并运行一切都很好,但是也很高兴能以某种方式使其在开发模式下工作。
I need to fetch data from an API that is pretty slow and seldom changes, so I thought I'd use an in-memory cache. I first tried a very simple approach by just saving it to a variable outside the scope of the loader function in my route:
let cache;
export const loader = async () => {
if (!cache) {
// we always end up here
cache = await (await fetch("...)).json()
}
}
but that didn't work. I then tried a proper caching library (lru-cache
), but that cache was also always empty. I then realized that the entired file got reloaded on each request which I guess is a dev mode thing, so I tried moving the creation of the cache to a separate file cache.server.ts and importing it from there.
import LRU from "lru-cache";
console.log("Creating cache"); // this is logged on each request
const cache = new LRU({ max: 200 });
export default cache;
But that file also seems to be reloaded on each request.
If I build a production version and run that everything works great, but it would be nice to have some way of getting it to work in dev mode as well.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
混音清除
需要
在开发中的每个请求中缓存以支持< livereload/>
。为了确保您的缓存能够存活这些清洗,您需要将其分配给global
对象。编辑:这是处理此此此操作的更好方法
Remix purges the
require
cache on every request in development to support<LiveReload/>
. To make sure your cache survives these purges, you need to assign it to theglobal
object.EDIT: Here's a better way to handle this
作为跟进乞力类人答案,这就是我的做法:
我在装载机中使用了它:
As a follow up on Kilimans answer, here's how I did it:
And I used it in the loader:
从乞力马族的更新答案,这是我使用 micro-memoize with typescript:
希望这可以帮助遇到相同问题的任何人,并且想使用比
node-cache更现代的东西
。再次感谢 kiliman 提供了更新的Singleton功能。
Following on from Kiliman's updated answer, here's how I did it using the micro-memoize package with TypeScript:
Hopefully this helps anyone who's having the same issue and wants to use something more modern than
node-cache
.Thanks again to Kiliman for providing the updated Singleton function.
我也这样做是为了将其放在服务器端。制作具有以下内容的文件,并在您要在哪里使用它。
I did this to have it at the server side as well. Make a file with the following content and call it wherever you want to use it.