A kind of factory and DI patterns library targeted to Typescript (w/o decorators).
Installation
How to use
License
To install Factsory, type the following:
- with NPM:
npm install factsory
- with YARN:
yarn add factsory
- It's possible to define a factory in two ways:
-
extending the
DefaultFactory
class:class MyFactory extends DefaultFactory<string> { instantiate(): string { return "value"; } }
-
implementing the
Factory
interface:class MyFactory implements Factory<string> { create(): string { return "value"; } }
-
To access the Container instance, just call the
Container.I
static method -
It's possible to define a customized Container implementation, useful for testing. You just need to implement the
ContainerSpec
interface as in the following example (based on jest-mock-extended):// using jest-mock-extended package const mockedSpec = mock<ContainerSpec>(); Container.impl = mockedSpec; // To reset to the default implementation, just call reset() Container.reset();
- A class or almost any other object can be registered in the Container, which can be done in two ways:
-
registering a class (e.g. a factory class - see Factory definition section):
// id = "MyFactory" Container.I.register(MyFactory); // or Container.I.register(MyFactory, { id: "MyFactoryCustomId" });
-
registering a creation function (factory method) using the
createFactoryMethod
:// id will be set to "" Container.I.register(createFactoryMethod(() => "value")); // or Container.I.register(createFactoryMethod(() => "value"), { id: "MyFactoryWithValue" }); // or Container.I.register(createFactoryMethod((params?: CreationParameters) => params?.args), { id: "MyFactoryWithArgs", args: "value" });
-
It's also possible to define dependencies, which will be injected during the object creation:
// the dependency class MyFactory extends DefaultFactory<string> { instantiate(): string { return "aValue"; } } // the target of the dependency injection class MyFactoryWithDependencies extends DefaultFactory<string> { protected readonly myFactory: MyFactory; constructor( params?: ContainerItemCreationDependencies<{ MyFactory: MyFactory; }> ) { super(); if (params?.dependencies) { this.myFactory = params.dependencies.MyFactory; } else { throw new Error("Invalid dependencies"); } if (!this.myFactory) { throw new Error("Invalid MyFactory dependency"); } } get dep(): MyFactory { return this.myFactory; } instantiate(): string { return "MyuFactoryWithDependencies"; } } // registering objects Container.I.register(MyFactory); Container.I.register(MyFactoryWithDependencies, { dependencies: [MyFactory], }); // will print 'aValue' console.log(Container.I.get(MyFactoryWithDependencies)?.dep.create());
- After registering a class or a creation function (factory method), it can also be claimed in two ways:
-
If it is a class, it can be claimed by the
Container.I.get
method using the class name as a parameter:Container.I.get(MyFactory);
-
If it is a creation function, it can be claimed by the
Container.I.get
method using the registered name as a parameter:Container.I.get("MyFactory");
-
It's possible to use the
LazyInstance
class to lazy initialize an object:let value = ""; const lazyInstance = new LazyInstance(() => (value = "initialized")); console.log(value); // prints "" console.log(lazyInstance.I); // prints "initialized" // or console.log(lazyInstance.getI()); // prints "initialized" console.log(value); // prints "initialized"
-
It's possible to use the
AsyncLazyInstance
class to lazy initialize an object:let value = ""; const asyncLazyInstance = new AsyncLazyInstance(async () => (value = "initialized")); console.log(value); // prints "" console.log(await asyncLazyInstance.I); // prints "initialized" // or console.log(await asyncLazyInstance.getI()); // prints "initialized" console.log(value); // prints "initialized"
-
It's also possible to use the
AsyncLazyInstance
class to lazy initialize an object with concurrency lock (mutex-like) control:let value = ""; const asyncLazyInstance = new AsyncLazyInstance( async () => (value = "initialized"), /** * Using async-mutex lib as an example * @see https://www.npmjs.com/package/async-mutex */ { lock: new Mutex() } ); console.log(value); // prints "" console.log(await asyncLazyInstance.I); // prints "initialized" // or console.log(await asyncLazyInstance.getI()); // prints "initialized" console.log(value); // prints "initialized"
Copyright (c) 2022 Tiago da Costa Peixoto [email protected]
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.