javascript - How to prevent Next.js from instantiating a singleton classobject multiple times? - Stack Overflow

I have an analytics utility like this:class Analytics {data: Record<string, IData>;constructor()

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.

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:

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. How can I achieve my use case for this?

I also tried using static instance but that doesn't work as well. Can someone help me in finding a solution to this?

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.

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:

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. How can I achieve my use case for this?

I also tried using static instance but that doesn't work as well. Can someone help me in finding a solution to this?

Share edited Feb 18, 2023 at 20:29 Youssouf Oumar 46.5k16 gold badges103 silver badges105 bronze badges asked Jan 29, 2023 at 5:54 Shivam SahilShivam Sahil 4,9557 gold badges51 silver badges90 bronze badges 0
Add a ment  | 

1 Answer 1

Reset to default 14

In development, Next clears Node.js cache on run, so every time there is a "piling..." in the terminal (which happens per page render), it starts as a new app, losing any previous variable.

This is why, in this article, down to the section where they instantiate a PrismaClient, to have it created only once, they use the global object, in your case, like so:

let analytics;

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

export default analytics;

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1743667622a4487242.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信