Where to start/init connections in a Class? Constructor or seperate dedicated method?

I’ve encountered this problem for Redis, Database, etc, which involves making a connections with connection strings provided by user.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>interface DataStorage<LockType, DataRef> {
acquireLock(resourceName: DataRef, ttl: number): Promise<LockType>;
releaseLock(lock: LockType): Promise<void>;
createData(data: string | number | Buffer, storageKey: DataRef): Promise<DataRef>;
readData(storageKey: DataRef): Promise<string>;
updateData(storageKey: DataRef, data: string | number | Buffer): Promise<void>;
close(): Promise<void>;
}
</code>
<code>interface DataStorage<LockType, DataRef> { acquireLock(resourceName: DataRef, ttl: number): Promise<LockType>; releaseLock(lock: LockType): Promise<void>; createData(data: string | number | Buffer, storageKey: DataRef): Promise<DataRef>; readData(storageKey: DataRef): Promise<string>; updateData(storageKey: DataRef, data: string | number | Buffer): Promise<void>; close(): Promise<void>; } </code>
interface DataStorage<LockType, DataRef> {
  acquireLock(resourceName: DataRef, ttl: number): Promise<LockType>;
  releaseLock(lock: LockType): Promise<void>;
  createData(data: string | number | Buffer, storageKey: DataRef): Promise<DataRef>;
  readData(storageKey: DataRef): Promise<string>;
  updateData(storageKey: DataRef, data: string | number | Buffer): Promise<void>;
  close(): Promise<void>;
}

This is my interface.
And here is the implementation example.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>export class RedisStorage implements DataStorage<Lock, string> {
private client: Redis | null = null;
private redlock: Redlock | null = null;
start() {
if (!this.client) {
this.client = new Redis(process.env.REDIS_URL!);
logger.info('Redis connection established: OK', { client_status: this.client.status });
// Handle connection errors
this.client.on('error', (error) => {
logger.error('ERROR: connecting to Redis!', { error: error });
throw new RedisStorageError(`ERROR: connecting to Redis: ${error}`);
});
}
if (!this.redlock) {
this.redlock = new Redlock([this.client]);
this.redlock.on('clientError', (error) => {
logger.error('ERROR: connecting to Redlock!', { error: error });
throw new RedisStorageError(`ERROR: connecting to Redlock: ${error}`);
});
}
}
async createData(data: string | number | Buffer, storageKey: string): Promise<string> {
try {
if (!this.client) {
this.start();
}
const value = await this.client!.set(storageKey, data);
logger.info(`${value}, Data created with key: ${storageKey}`);
return storageKey;
} catch (error) {
logger.error('ERROR: creating data in redis!', { error: error });
throw new RedisStorageError('ERROR: creating data: ' + error);
}
}
</code>
<code>export class RedisStorage implements DataStorage<Lock, string> { private client: Redis | null = null; private redlock: Redlock | null = null; start() { if (!this.client) { this.client = new Redis(process.env.REDIS_URL!); logger.info('Redis connection established: OK', { client_status: this.client.status }); // Handle connection errors this.client.on('error', (error) => { logger.error('ERROR: connecting to Redis!', { error: error }); throw new RedisStorageError(`ERROR: connecting to Redis: ${error}`); }); } if (!this.redlock) { this.redlock = new Redlock([this.client]); this.redlock.on('clientError', (error) => { logger.error('ERROR: connecting to Redlock!', { error: error }); throw new RedisStorageError(`ERROR: connecting to Redlock: ${error}`); }); } } async createData(data: string | number | Buffer, storageKey: string): Promise<string> { try { if (!this.client) { this.start(); } const value = await this.client!.set(storageKey, data); logger.info(`${value}, Data created with key: ${storageKey}`); return storageKey; } catch (error) { logger.error('ERROR: creating data in redis!', { error: error }); throw new RedisStorageError('ERROR: creating data: ' + error); } } </code>
export class RedisStorage implements DataStorage<Lock, string> {
  private client: Redis | null = null;
  private redlock: Redlock | null = null;

  start() {
    if (!this.client) {
      this.client = new Redis(process.env.REDIS_URL!);
      logger.info('Redis connection established: OK', { client_status: this.client.status });

      // Handle connection errors
      this.client.on('error', (error) => {
        logger.error('ERROR: connecting to Redis!', { error: error });
        throw new RedisStorageError(`ERROR: connecting to Redis: ${error}`);
      });
    }

    if (!this.redlock) {
      this.redlock = new Redlock([this.client]);
      this.redlock.on('clientError', (error) => {
        logger.error('ERROR: connecting to Redlock!', { error: error });
        throw new RedisStorageError(`ERROR: connecting to Redlock: ${error}`);
      });
    }
  }

  async createData(data: string | number | Buffer, storageKey: string): Promise<string> {
    try {
      if (!this.client) {
        this.start();
      }
      const value = await this.client!.set(storageKey, data);
      logger.info(`${value}, Data created with key: ${storageKey}`);
      return storageKey;
    } catch (error) {
      logger.error('ERROR: creating data in redis!', { error: error });
      throw new RedisStorageError('ERROR: creating data: ' + error);
    }
  }

Do we create seperate start method, and make a lazy initialisation or is it better to create connections in constructor itself?

Is this acceptable way below?

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>export class RedisBroker implements MessageBroker {
private readonly client: Redis;
private readonly subscriber: Redis;
private readonly callbacks: Map<string, (message: string) => void> = new Map();
/**
* Creates a new instance of the RedisBroker class.
* @param redisServerUrl - A string representing the URL of the Redis server to connect to.
*
* @example
* const messageBroker = new RedisBroker('redis://localhost:6379');
* await messageBroker.publish('my-channel', 'hello world');
* await messageBroker.subscribe('my-channel', (message) => {
* console.log(message);
* });
*/
constructor(redisServerUrl: string) {
this.client = new Redis(redisServerUrl, { connectTimeout: 10000 });
this.subscriber = new Redis(redisServerUrl, { connectTimeout: 10000 });
// Handle connection errors
this.client.on('error', (error) => {
throw new Error(`ERROR: connecting to Redis: ${error}`);
});
this.client.on('error', (error) => {
throw new Error(`ERROR: connecting to Redis: ${error}`);
});
// Set up message event listener on the subscriber client
this.subscriber.on('message', (channel: string, message: string) => {
const callback = this.callbacks.get(channel);
if (callback) {
logger.info(`REDIS SUB: Received message on channel: ${channel}`);
callback(message);
}
});
</code>
<code>export class RedisBroker implements MessageBroker { private readonly client: Redis; private readonly subscriber: Redis; private readonly callbacks: Map<string, (message: string) => void> = new Map(); /** * Creates a new instance of the RedisBroker class. * @param redisServerUrl - A string representing the URL of the Redis server to connect to. * * @example * const messageBroker = new RedisBroker('redis://localhost:6379'); * await messageBroker.publish('my-channel', 'hello world'); * await messageBroker.subscribe('my-channel', (message) => { * console.log(message); * }); */ constructor(redisServerUrl: string) { this.client = new Redis(redisServerUrl, { connectTimeout: 10000 }); this.subscriber = new Redis(redisServerUrl, { connectTimeout: 10000 }); // Handle connection errors this.client.on('error', (error) => { throw new Error(`ERROR: connecting to Redis: ${error}`); }); this.client.on('error', (error) => { throw new Error(`ERROR: connecting to Redis: ${error}`); }); // Set up message event listener on the subscriber client this.subscriber.on('message', (channel: string, message: string) => { const callback = this.callbacks.get(channel); if (callback) { logger.info(`REDIS SUB: Received message on channel: ${channel}`); callback(message); } }); </code>
export class RedisBroker implements MessageBroker {
  private readonly client: Redis;
  private readonly subscriber: Redis;
  private readonly callbacks: Map<string, (message: string) => void> = new Map();

  /**
   * Creates a new instance of the RedisBroker class.
   * @param redisServerUrl - A string representing the URL of the Redis server to connect to.
   *
   * @example
   * const messageBroker = new RedisBroker('redis://localhost:6379');
   * await messageBroker.publish('my-channel', 'hello world');
   * await messageBroker.subscribe('my-channel', (message) => {
   *  console.log(message);
   *  });
   */
  constructor(redisServerUrl: string) {
    this.client = new Redis(redisServerUrl, { connectTimeout: 10000 });
    this.subscriber = new Redis(redisServerUrl, { connectTimeout: 10000 });

    // Handle connection errors
    this.client.on('error', (error) => {
      throw new Error(`ERROR: connecting to Redis: ${error}`);
    });
    this.client.on('error', (error) => {
      throw new Error(`ERROR: connecting to Redis: ${error}`);
    });

    // Set up message event listener on the subscriber client
    this.subscriber.on('message', (channel: string, message: string) => {
      const callback = this.callbacks.get(channel);
      if (callback) {
        logger.info(`REDIS SUB: Received message on channel: ${channel}`);
        callback(message);
      }
    });

6

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật