0

I am trying to implement a singleton pattern for the fastify instance. My code is as follows :-


const { createFastifyServer: server } = require("../app");

const getFastifyInstance = (() => {
  let fastify;
  return {
    fastifyInstance: async () => {
      if (!fastify) {
        console.log("Called")
        fastify = server();
        await fastify.ready();
      }
      return fastify
    }
  }
})();

const { fastifyInstance } = getFastifyInstance
module.exports = fastifyInstance

Now wherever I am importing the code in a different file, the console prints "Called" each time it's imported in a new file, but shouldn't that be only once if singleton pattern was correctly implemented. Any idea what am I doing wrong?

Tanmaya
  • 570
  • 1
  • 4
  • 10
  • How do you call this file? Are you awaiting fastify instance? – Manuel Spigolon Mar 03 '21 at 21:33
  • Yes, I am using await while calling the fastify instance. Execution wise there's no error. But don't know why its not working. I am using this inside test files (jest, inside beforeAll). Still no clue why is it behaving differently? – Tanmaya Mar 04 '21 at 05:27
  • Would you mind to add a complete example? This snippet looks good – Manuel Spigolon Mar 04 '21 at 08:50
  • 1
    I got the issue..I tried to replicate the implementation and ran the files, it was working correctly...while in jest it does not work ...had to search a little and found this https://github.com/facebook/jest/issues/5120... Thanks for the help @Manuel Spigolon – Tanmaya Mar 04 '21 at 13:28

0 Answers0