well i have a question regarding the best way to code this situation: i have a class where i need to have a static variable in all the project: connection
singleton without name space:
class Broker {
static connection: Connection = undefined;
static channel: Channel = undefined;
static urli: string = process.env.RABBIT_URL || 'url';
static start() {
return new Promise<Connection>((resolve, reject) => {
if (Broker.connection || !Broker.urli) {
const message = !Broker.urli
? 'The host of rabbitmq was not found in the environment variables'
: 'Connection has already been established';
logger.info(message);
reject(new Error(message));
}
retry<Connection>(() => connect(Broker.urli), 10, 1000)
.then((conn) => {
Broker.connection = conn;
resolve(conn);
})
.catch((err) => reject(new Error(err)));
});
}
}
export const ConnectionMQ: Connection = Broker.connection;
export const ChannelMQ: Channel = Broker.channel;
export const start = () => {
return Broker.start();
};
with namespace
//namespace
namespace Broker {
export type QueuesToAssert = { queue: string; options?: Options.AssertQueue };
export type ExchangesToAssert = {
exchange: string;
type: string;
options?: Options.AssertExchange;
};
export type QueuesToBind = {
queue: string;
source: string;
pattern: string;
args?: any;
};
//static
class BrokerMain {
static connection: Connection = undefined;
static channel: Channel = undefined;
static urli: string = process.env.RABBIT_URL || 'url';
static start() {
return new Promise<Connection>((resolve, reject) => {
if (BrokerMain.connection || !BrokerMain.urli) {
const message = !BrokerMain.urli
? 'The host of rabbitmq was not found in the environment variables'
: 'Connection has already been established';
logger.info(message);
reject(new Error(message));
}
retry<Connection>(() => connect(BrokerMain.urli), 10, 1000)
.then((conn) => {
this.connection = conn;
resolve(conn);
})
.catch((err) => reject(new Error(err)));
});
}
}
export const Connection = BrokerMain.connection;
export const Channel = BrokerMain.channel;
export const start = () => {
return BrokerMain.start();
};
export const close = () => {};
}
//usage
const connection = Broker.Connection ? Broker.start() : undefined;
I would like to know what is the best / correct option in this situation, or if I could apply another way to the situation. remembering that I only need 2 unique variables of the class that are unique statics throughout the project. I have doubts if the singleton is needed in this case or just static already solves
namespace Broker {}wrapper from the namespace example and he happyexport let Connection: Connection; then changethis.connection = conntoConnection = conn. That will fix an existing bug and simply your codeexport letfor the connection and you need set it when you get the connection in your call back. The problem with your current implementation is that the value never gets updated.export const ConnectionMQ: Connection = Broker.connectionwill always be undefined.