简体   繁体   English

如何防止 Next.js 多次实例化相同的 object,每次导入一个?

[英]How to prevent Next.js from instantiating the same object multiple time, one per import?

I have an analytics utility like this:我有一个这样的分析实用程序:

class Analytics {
    data: Record<string, IData>;

    constructor() {
        this.data = {};
    }
    setPaths(identifier: string) {
        if (!this.data[identifier])
            this.data[identifier] = {
                generic: getGenericInit(),
                session: getSessionInit(),
                paths: {
                    geoCollectionPath: '',
                    sessionCollectionPath: '',
                    eventsCollectionPath: ''
                }
            };
        this.data[identifier].paths = {
            geoCollectionPath: getGeoPath(identifier),
            sessionCollectionPath: getSessionPath(identifier),
            eventsCollectionPath: getEventPath(identifier)
        };
    }
    getAll() {
        return this.data;
    }
}

const analytics = new Analytics();
export default analytics;

And I import it into 2 api folders: e1.ts and e2.ts .我将它导入 2 api 文件夹: e1.tse2.ts

e1.ts : e1.ts

import { NextApiHandler } from 'next';
import analytics from '@/firebase/v2/analytics';

const handler: NextApiHandler = (req, res) => {
    analytics.setPaths('abc');
    return res.status(201).end();
};
export default handler;

and e2.ts :e2.ts

import { NextApiHandler } from 'next';
import analytics from '@/firebase/v2/analytics';

const handler: NextApiHandler = (req, res) => {
    return res.status(200).json(analytics.getAll());
};
export default handler;

Now even when I add the data by hitting /api/e1 since the import instantiates a fresh class in e2 , I fail to retrieve the data from /api/e2 .现在,即使我通过点击/api/e1添加数据,因为导入在e2中实例化了一个新的 class ,我也无法从/api/e2检索数据。 How can I achieve my use case for this?我怎样才能实现我的用例呢?

I also tried using static instance but that doesn't work as well.我也尝试使用static实例,但效果不佳。 Can someone help me in finding a solution to this?有人可以帮我找到解决方案吗?

In this article written by the Next.js team, if you go down to the section where they instantiate a PrismaClient , to not have a new instance in development, they use the global object, like so:在这篇由 Next.js 团队撰写的文章中,如果您 go 到他们实例化PrismaClient的部分,为了不在开发中有新实例,他们使用global object,如下所示:

class Analytics {
  //...
}

let analytics: Analytics;

if (process.env.NODE_ENV === "production") {
  analytics = new Analytics();
} else {
  if (!global.analytics) {
    global.analytics = new Analytics();
  }
  analytics = global.analytics;
}

export default analytics;

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

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