1.2.1 • Published 4 years ago

provy v1.2.1

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

Provy

Simple and versatile dependency injection container.

Installation

npm install provy

Or

yarn add provy

Usage

import { Container, Identifier } from 'provy';

type UserService = {
    getUser(id: string): Promise<User>;
};

class UserServiceImpl implements UserService {
    private readonly apiUrl: string;

    constructor(apiUrl: string) {
        this.apiUrl = apiUrl;
    }

    getUser(id) {
        return fetch(`${this.apiUrl}/users/${id}`)
            .then((response) => response.data)
            .catch((error) => {
                throw new Error(`An error occurred: ${error.message}`);
            });
    }
}

const container = new Container();
const identifiers = {
    apiUrl: new Identifier<string>('API_URL'),
    userService: new Identifier<UserService>('USER_SERVICE'),
};

container.bindConstant(identifiers.apiUrl, 'https://api.example.com');
container.bindMemoized(identifiers.userService, () => {
    return new UserServiceImpl(container.resolve(identifiers.apiUrl));
});

API

Container

.alias(identifier, resolveTo)

Registers an alias to another dependency.

.bindConstant(identifier, value)

Registers a constant value.

.bindDynamic(identifier, factory)

Registers a factory function. The factory is called every time a value is requested with resolve().

.bindMemoized(identifier, factory)

Registers a factory function, which is called only once. The result is then memoized and returned with subsequent calls to resolve().

.isBound(identifier)

Checks if a dependency is regsitered for the given identifier.

.resolve(identifier)

Returns the value registered for the given identifier. If the identifier is not registered an error is thrown.

.unbind(identifier)

Unregisters the dependency associated to the given identifier.

Identifier

An Identifier is used to identify a dependency within a Container. It accepts a generic type which is used to type the return value of the Container.resolve() function.

.name

The name with which the identifier has been created.

License

MIT