I am trying to make a Singleton class to save some variable and use it from other class. But I am getting following error when I am trying to access it.
TypeError: Singleton.createInstance is not a function
at /Users/pankajsachdeva/Desktop/Pankaj/My Code/SmilaApp/SmilaApi/app.js:17:35
at Layer.handle [as handle_request] (/Users/pankajsachdeva/node_modules/express/lib/router/layer.js:95:5)
at next (/Users/pankajsachdeva/node_modules/express/lib/router/route.js:137:13)
at Route.dispatch (/Users/pankajsachdeva/node_modules/express/lib/router/route.js:112:3)
at Layer.handle [as handle_request] (/Users/pankajsachdeva/node_modules/express/lib/router/layer.js:95:5)
at /Users/pankajsachdeva/node_modules/express/lib/router/index.js:281:22
at Function.process_params (/Users/pankajsachdeva/node_modules/express/lib/router/index.js:341:12)
at next (/Users/pankajsachdeva/node_modules/express/lib/router/index.js:275:10)
at expressInit (/Users/pankajsachdeva/node_modules/express/lib/middleware/init.js:40:5)
at Layer.handle [as handle_request] (/Users/pankajsachdeva/node_modules/express/lib/router/layer.js:95:5)
Following is my Singelton class:
var mySingleton = (function() {
let instance;
let message;
function createInstance() {
if (!instance) instance = { setMessage, getMessage };
return instance;
}
function setMessage(newMessage) {
message = newMessage;
}
function getMessage() {
return message;
}
return { createInstance }
})();
I am trying to use it in following class:
const express = require('express')
const Singleton = require('./mySingleton');
const app = express()
const port = 3000
app.post('/readyforunlock', (req, res) => {
var firstInstance = Singleton.createInstance();
firstInstance.setMessage("Message");
console.log(firstInstance.getMessage());
res.send(firstInstance.getMessage());
})
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})
I am very new to Node.js and not able to figure out why is it not working. I am trying to set some variable in one api and access it from another api. I am trying to achieve this using Singleton. Also please let me know if this correct approach or there are better options.
Regards