我需要从一个非常慢且很少变化的 API 获取数据,所以我想我应该使用内存缓存。我首先尝试了一种非常简单的方法,只需将其保存到路径中加载器函数范围之外的变量中:
let cache;
export const loader = async () => {
if (!cache) {
// we always end up here
cache = await (await fetch("...)).json()
}
}
但这没有用。然后我尝试了一个合适的缓存库(lru-cache
),但该缓存也始终为空。然后我意识到每个请求都会重新加载整个文件,我猜这是开发模式的事情,所以我尝试将缓存的创建移动到一个单独的文件中缓存服务器.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;
但该文件似乎也会根据每个请求重新加载。
如果我构建一个生产版本并运行一切都很好,但如果有某种方法让它在开发模式下工作也很好。
混音清除require
缓存开发中的每个请求以支持<LiveReload/>
。为了确保您的缓存在这些清除中幸存下来,您需要将其分配给global
object.
编辑:这是处理这个问题的更好方法
// utils/singleton.server.ts
// since the dev server re-requires the bundle, do some shenanigans to make
// certain things persist across that ????
// Borrowed/modified from https://github.com/jenseng/abuse-the-platform/blob/2993a7e846c95ace693ce61626fa072174c8d9c7/app/utils/singleton.ts
export function singleton<Value>(name: string, value: () => Value): Value {
const yolo = global as any
yolo.__singletons ??= {}
yolo.__singletons[name] ??= value()
return yolo.__singletons[name]
}
// utils/prisma.server.ts
import { PrismaClient } from '@prisma/client'
import { singleton } from './singleton.server.ts'
const prisma = singleton('prisma', () => new PrismaClient())
prisma.$connect()
export { prisma }
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)