1.0.0 • Published 5 years ago

@easy-two/singleton-decorator v1.0.0

Weekly downloads
1
License
MIT
Repository
github
Last release
5 years ago

Singleton decorator

A decorator to create one and only instance of any class.

Install

npm install @easy-two/typescript-singleton-decorator --save

Usage

@Singleton()
class Service {
    method() {}
}

const a = new Service();
const b = new Service();

console.log(a === b) // output: true

As a result you will always get the same instance of class.
Also this package can be used to solve shared angular services in lazy modules problem https://angular.io/guide/ngmodule-faq#why-is-it-bad-if-a-shared-module-provides-a-service-to-a-lazy-loaded-module.

API

Singleton.getCache() - method to get cache (and change, clear, fill it)
Singleton.hashCode(class) - method to get cache key for class, passed in arguments
Singleton.disable() - method to call new on class with original constructor
Singleton.enable() - method to activate singleton decorator after it was disable

Warning - your tests can be affected

This decorator works at the file system level - so first time created instance it will live as long as your application. So please use disable and enable methods for your singleton class tests to keep tests encapsulation.

beforeEach(() => {
    Singleton.disable();
})

afterEach(() => {
    Singleton.enable();
})

or disable it globally in entry file of your tests calling Singleton.disable().