简体   繁体   English

Next.js:如何在服务器端持久化数据以从页面调用访问它

[英]Next.js: how to persist data server-side to access it from page calls

I have a Next.js app with a custom server (Express) that does some stuff continuously and keeps some data in memory as long as the server is alive.我有一个带有自定义服务器 (Express) 的 Next.js 应用程序,它会持续执行一些操作,并且只要服务器处于活动状态,就会将一些数据保存在内存中。

I want to access this data from the API calls (pages).我想从 API 调用(页面)访问这些数据。 What is the proper way to store and access it?存储和访问它的正确方法是什么?

My server index file:我的服务器索引文件:

    import { createServer } from 'http'
    import express from 'express'
    import { parse } from 'url'
    import next from 'next'
    import pinoHttp from 'pino-http'
    
    const logger = pinoHttp()
    const dev = process.env.NODE_ENV !== 'production'
    const nextApp = next({ dev })
    
    try {
      const handle = nextApp.getRequestHandler()
      const port = process.env.NODE_PORT || 3000
      
      nextApp.prepare().then(() => {
        const app = express()
        app.locals.myArray = []
        
        // Do stuff in the background that will update the array
        
        createServer((request, response) => {
          const parsedUrl = parse(request.url, true)

          logger(request, response)
          handle(request, response, parsedUrl)
        }).listen(port, (error?: Error) => {
          if (error) throw error
        
          console.log(`Listening on: http://localhost:${port}`)
        })
      })
    } catch (error) {
      console.log(error)
      process.exit(1)
    }

My page:我的页面:

    import { Request, Response } from 'express'
    
    export default async function (request: Request, response: Response): Promise<void> {
      // Here, request.app and response.app are both undefined.
    }

If your data only needs to persist as long as your nodejs program is running you can store it in RAM using the Map object .如果您的数据只需要在您的 nodejs 程序运行时持久保存,您可以使用Map 对象将其存储在 RAM 中。 Maps are collections of key / value pairs much like C# Dictionaries, python dictionaries, or php arrays.映射是键/值对的集合,很像 C# 词典、python 词典或 php 数组。

You can create this object just once when you start up and then attach it to your Express app object like so.你可以在启动时只创建一次这个对象,然后像这样将它附加到你的 Express app对象。

var app = express();
app.locals.myMap = new Map()

Then, in each route handler you can refer to it like so.然后,在每个路由处理程序中,您可以像这样引用它。

const myMap = req.app.locals.myMap

Then you can write code like this:然后你可以写这样的代码:

let userdata = {}
const username = 'whatever'
if(myMap.has(username)) {
   userdata = myMap.get(username)
}
...
myMap.set(username, userdata)

This particular example stores a userdata object in the Map for each username .这个特定的例子在 Map 中为每个username存储一个userdata对象。

Obviously the Map vanishes without a trace if your nodejs stops for whatever reason.显然,如果您的 nodejs 因任何原因停止,地图就会消失得无影无踪。

You can put anything you like in app.locals ;你可以在app.locals放任何你喜欢的app.locals it doesn't have to be a Map.它不一定是地图。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM