0

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

7
  • Neither is appropriate. Use modules. Basically, remove the namespace Broker {} wrapper from the namespace example and he happy Commented Sep 9, 2020 at 23:51
  • but that way will my connection from the class Broker have a static value throughout the project? Commented Sep 9, 2020 at 23:53
  • Of course. But you would do export let Connection: Connection; then change this.connection = conn to Connection = conn. That will fix an existing bug and simply your code Commented Sep 10, 2020 at 0:03
  • I edited the code based on that, could you tell me if this is it? the first code block Commented Sep 10, 2020 at 0:14
  • 1
    That's very close to what I meant but if you look at my last comment, you need to use export let for 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.connection will always be undefined. Commented Sep 10, 2020 at 0:22

1 Answer 1

1

I would like to know what is the best / correct option in this situation,

I would definitely recommend the static class methods.

Reason

namespace is a TypeScript only feature and not supported by many tools out of the box e.g. Create React App.

Sign up to request clarification or add additional context in comments.

2 Comments

basarat and in this situation where I said that I only need 2 static variables: connection and channel, that is, just one value in the entire project, would I need to use singleton for this? or just declaring the variable as static would solve it already?
A static is a singleton 👍

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.