最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How do I use in-memory cache in Remix.run dev mode? - Stack Overflow

programmeradmin6浏览0评论

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.

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.

Share Improve this question edited Jul 18, 2022 at 14:51 André Werlang 5,9541 gold badge37 silver badges50 bronze badges asked Jun 17, 2022 at 16:00 mflodinmflodin 1,1231 gold badge12 silver badges22 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 10

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 the global object.

EDIT: Here's a better way to handle this

// utils/singleton.server.ts

// since the dev server re-requires the bundle, do some shenanigans to make
// certain things persist across that 
发布评论

评论列表(0)

  1. 暂无评论