如何在 Next.js 中的服务器启动时运行一次仅服务器代码?

问题描述 投票:0回答:1

我正在尝试从

User
getStaticProps
访问我的
getStaticPaths
objection.js 模型。

但是,我需要跑步

import Knex from "knex";
import knexfile from "./knexfile";
import { Model } from "objection";

function setupDB() {
  const db = Knex(knexfile[process.env.NODE_ENV]);
  Model.knex(db);
}

服务器启动时。

当我这样做时

  const users = await User.query();

getStaticPaths
内部,我收到
Error: no database connection available for a query. You need to bind the model class or the query to a knex instance.
错误。

我尝试在

setupDB()
内运行
_app.js
并进行
typeof window === "undefined"
检查,但仅导入 Knex 并在
_app.js
中反对会引发错误。

我应该在哪里运行这个?我真的真的很想避免延长

server.js

(我应该补充一下,next.js github 上有过讨论,但不确定是否有一种方法可以针对 Objection.js 或任何最近的开发进行具体操作。

next.js prisma objection.js
1个回答
0
投票

Next.js v13.2.0 为此在服务器启动时运行的 App Router 中提供了一个名为

instrumentationHook
的功能。要使用它,请将
instrumentationHook
 中的 
next.config.js

功能标志设置为 true
// next.config.js

module.exports = {
  experimental: {
    instrumentationHook: true,
  },
}

然后创建一个

app/instrumentation.{js,ts,...}
文件

// app/instrumentation.js

import Knex from "knex";
import knexfile from "./knexfile";
import { Model } from "objection";

function setupDB() {
  const db = Knex(knexfile[process.env.NODE_ENV]);
  Model.knex(db);
}

当您运行

next start
(或独立模式下运行
node .next/server.js
)时,该文件将被执行一次。

© www.soinside.com 2019 - 2024. All rights reserved.