@dmitriyzverev/pod
v1.0.0-dev.0
Published
_Simple implementation of Service Locator pattern with singletons and lazy loading_
Downloads
2
Readme
@dmitriyzverev/pod
Simple implementation of Service Locator pattern with singletons and lazy loading
Intro
There are two main entities: pod and seed. Pod is a container for seeds. Seed is a function that get pod as an argument and returns some value. Seed can use any other seed from pod as a dependency. It is a way to organize your code into small pieces, that can be easily tested and reused.
Usage
Install dependencies:
npm i -SE @dmitriyzverev/pod
Create pod and define your seeds inside:
import {createPod} from '@dmitriyzverev/pod'; const pod = createPod({ seeds: { get user() { return { name: 'Bob', }; }, get helloMessage() { return `Hello, ${pod.user.name}!`; // use "user" seed as a dependency }, }, });
Now you can use any seed defined in pod:
console.log(pod.helloMessage); // Hello, Bob!
Advanced usage
Singletons
By default, each seed is a singleton. It will be created only once, and only if
requested. If you need to create a new seed instance for each seed request,
disable the seed singleton in the singletons
property:
import {createPod} from '@dmitriyzverev/pod';
const pod = createPod({
seeds: {
get user() {
return {
name: 'Bob',
};
},
},
singletons: {
user: false, // disable singleton for "user" seed
},
});
console.log(pod.user === pod.user); // false - each request creates a new instance
Exclude and include seeds
If you need to exclude some seeds from pod, use exclude
property:
import {createPod} from '@dmitriyzverev/pod';
const pod = createPod({
seeds: {
get foo() {
return 'foo';
},
get bar() {
return 'bar';
},
get baz() {
return 'baz';
},
},
});
const podWithoutFoo = pod.exclude('foo');
console.log(podWithoutFoo.foo); // undefined
Or you can include only some seeds:
const podWithFooAndBar = pod.include('foo', 'bar');
console.log(podWithFooAndBar.foo); // 'foo'
console.log(podWithFooAndBar.baz); // undefined
Both exclude
and include
methods create a new pod instance, so you can use
them and don't worry about the original pod:
console.log(pod.foo); // 'foo' - still available in the original pod