Need private packages and team management tools?Check out npm Teams »

@easy-two/singleton-decorator

1.0.0 • Public • Published

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().

Install

npm i @easy-two/singleton-decorator

DownloadsWeekly Downloads

1

Version

1.0.0

License

MIT

Unpacked Size

84 kB

Total Files

20

Last publish

Collaborators

  • avatar
  • avatar