是否可以在构建时发出 API 请求,并将其缓存起来,以便它可在内存中用于所有未来的 SSR 请求?
我的用例是我有渲染服务器端所需的数据(出于 SEO 原因),但它存储在数据库中。
我不想为每个 SSR 请求发出此 API 请求。
理想情况下:
我研究了一些 SO 答案,所有似乎都指向基于 Redis 的缓存。有没有办法在内存中做到这一点。
例如,我使用nuxtServerInit:
async nuxtServerInit({ dispatch, commit }, context: Context) {
// check if already in memory?
if (somehowInMemory) {
commit(cache)
} else {
const serverDataJson = await dispatch("getServerData");
// store this json in memory?
cache = serverDataJson;
commit(cache);
}
}
Run Code Online (Sandbox Code Playgroud)
这是我到目前为止所使用的:
构建模块
import fs from "fs";
const getCachedApiRequests: Module<Options> = async function () {
const data = await getData();
fs.writeFileSync("./data.json", JSON.stringify(data), "utf8");
}
const config: NuxtConfig = {
buildModules: [
async () => {
await getCachedApiRequests();
}
]
}
Run Code Online (Sandbox Code Playgroud)
nuxtServerInit.ts
import data from "./data.json";
export async function nuxtServerInit({ dispatch, commit }, context) {
commit('setData', data);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2951 次 |
| 最近记录: |