我有以下实用函数,它只是一个用于存储计数器的单例类。
export class CounterSingleton {
private static instance: CounterSingleton;
private count: number;
private constructor() {
this.count = 0;
}
public static getInstance(): CounterSingleton {
if (!CounterSingleton.instance) {
CounterSingleton.instance = new CounterSingleton();
}
return CounterSingleton.instance;
}
public increment(): void {
this.count++;
}
public getCount(): number {
return this.count;
}
}
我希望在 api 路由中可以访问计数器类实例。我对此没有问题。
// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
import { CounterSingleton } from "@/utility/counter";
import type { NextApiRequest, NextApiResponse } from "next";
type Data = {
counter: number;
};
export default function handler(
req: NextApiRequest,
res: NextApiResponse<Data>
) {
const counter = CounterSingleton.getInstance();
counter.increment();
res.status(200).json({ counter: counter.getCount() });
}
第一次 api 调用:{ counter: 1 }
第二次 api 调用:{ counter: 2 }
当我访问中间件中的同一个计数器类时。它总是给我计数器为 0.
import { NextResponse } from "next/server";
import { CounterSingleton } from "./utility/counter";
export function middleware() {
const counter = CounterSingleton.getInstance();
console.log(counter.getCount());
return NextResponse.next();
}
有人可以向我解释为什么中间件中的单例实例不同吗?
中间件可能在 API 路由之前执行。这意味着 API 还没有增加 CounterSingleton 类的实例;中间件在递增之前可以访问单例实例。这就是为什么它返回 0.