gpt4 book ai didi

javascript - 如何在 Remix.run 开发模式下使用内存缓存?

转载 作者:行者123 更新时间:2023-12-02 15:50:29 25 4
gpt4 key购买 nike

我需要从一个非常慢且很少更改的 API 中获取数据,因此我想我会使用内存缓存。我首先尝试了一种非常简单的方法,将其保存到我的路由中加载程序函数范围之外的变量中:

let cache;

export const loader = async () => {
if (!cache) {
// we always end up here
cache = await (await fetch("...)).json()
}
}

但这没有用。然后我尝试了一个合适的缓存库 (lru-cache),但那个缓存也总是空的。然后我意识到每个请求都会重新加载整个文件,我猜这是开发模式的事情,所以我尝试将缓存的创建移动到一个单独的文件 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;

但该文件似乎也会在每次请求时重新加载。

如果我构建了一个生产版本并运行它,一切都很好,但如果有某种方法让它也能在开发模式下工作,那就太好了。

最佳答案

Remix 清除了 require缓存开发中的每个请求以支持 <LiveReload/> .为了确保您的缓存在这些清除后仍然存在,您需要将其分配给 global对象。

这是笑话教程中的一个例子

import { PrismaClient } from "@prisma/client";

let db: PrismaClient;

declare global {
var __db: PrismaClient | undefined;
}

// this is needed because in development we don't want to restart
// the server with every change, but we want to make sure we don't
// create a new connection to the DB with every change either.
if (process.env.NODE_ENV === "production") {
db = new PrismaClient();
} else {
if (!global.__db) {
global.__db = new PrismaClient();
}
db = global.__db;
}

export { db };

https://remix.run/docs/en/v1/tutorials/jokes#connect-to-the-database

关于javascript - 如何在 Remix.run 开发模式下使用内存缓存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72661999/

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