Singleton class in javascript with conditional parameter

Viewed 448

I have two classes :

useService.ts

import { useMemo } from 'react';

/**
 * Hook will take the singletone service instance later keeping it memoized
 * @param service
 */
export function useService<T> ( service: { new (): T; getInstance (): T } ): T {
    return useMemo<T>(() => service.getInstance(), []);
}

/**
 * Hook will take instance of the given class memoized
 * @param Class
 * @param args
 */
export function useClass<S, A extends []> ( Class: { new ( ...args: A ): S }, ...args: A ): S {
    return useMemo<S>(() => new Class(...args), []);
}

CartService.ts

var CART_ITEMS_KEY = 'SOME_KEY';

export class CartService {
private static __SELF__: CartService;
private __items: CartItem[] = [];
private auth: AuthService;
private api: APIService;
private endpoint: AxiosInstance;

constructor (cartItemsKey) {
    CART_ITEMS_KEY = cartItemsKey;
    this.auth = AuthService.getInstance();
    this.api = APIService.getInstance();
    this.endpoint = this.api.createEndpoint('cart');

    this.init();
}

/**
 * Get singletone service instance
 */
public static getInstance (): CartService {
    if ( !CartService.__SELF__ ) {
        CartService.__SELF__ = new CartService();
    }

    return CartService.__SELF__;
}
}

I want to initialize a CartService object and pass it in userService like this.

useService(CartService("SOME_NEW_KEY"))

I have tried many approaches but getting errors.

2 Answers

userService(CartService("SOME_NEW_KEY")) It's invalid syntax in typescript you might get error like Value of type 'typeof CartService' is not callable.

While instantiating CartService we need to pass cartItemsKey to the constructor.

  /**
   * Get singleton service instance
   */
  public static getInstance(cartItemsKey): CartService {
    if (!CartService.__SELF__) {
      CartService.__SELF__ = new CartService(cartItemsKey);
    }

    return CartService.__SELF__;
  }

Call like below

userService(CartService.getInstance("SOME_NEW_KEY"))

Try this:

useService.ts

import { useMemo } from 'react';

/**
 * Hook will take the singleton service instance later keeping it memoized
 * @param service
 */
export function useService<T>(
  service: {
    new (): T;
    getInstance(...args: String[]): T;
  },
  args: String[]
): T {
  return useMemo<T>(() => service.getInstance(...args), []);
}

/**
 * Hook will take instance of the given class memoized
 * @param Class
 * @param args
 */
export function useClass<S, A extends []>(
  Class: { new (...args: A): S },
  ...args: A
): S {
  return useMemo<S>(() => new Class(...args), []);
}

CartService.ts

export class CartService {
  private static __SELF__: CartService;
  private cartItemsKey: String;
  private cartId: String;

  constructor(cartItemsKey: String = 'default', cartId: String = 'default') {
    this.cartItemsKey = cartItemsKey;
    this.cartId = cartId;
  }

  log() {
    console.log('cartId: ' + this.cartId);
    console.log('cartItemsKey: ' + this.cartItemsKey);
  }

  /**
   * Get singletone service instance
   */
  public static getInstance(...args: String[]): CartService {
    if (!CartService.__SELF__) {
      CartService.__SELF__ = new CartService(...args);
    }

    return CartService.__SELF__;
  }
}

And then use it like this:

let cartService = useService(CartService, [
    'SOME_KEY_FROM_TEST',
    'SOME_ID_FROM_TEST'
  ]);
cartService.log()
Related