Nuxt:有没有办法在内存中跨请求缓存服务器端?

d-_*_*_-b 5 nuxt.js

是否可以在构建时发出 API 请求,并将其缓存起来,以便它可在内存中用于所有未来的 SSR 请求?

我的用例是我有渲染服务器端所需的数据(出于 SEO 原因),但它存储在数据库中。

我不想为每个 SSR 请求发出此 API 请求。


理想情况下:

  1. 在构建时发出一次 API 请求
  2. 访问或提交此数据到 Vuex
  3. 不必在每个 SSR 上请求此操作
  4. 每24小时刷新一次数据

我研究了一些 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)

d-_*_*_-b 1

这是我到目前为止所使用的:

构建模块

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)