0.4.0 • Published 5 years ago

@squirly/di v0.4.0

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

@squirly/di

CircleCI semantic-release standard-readme compliant Commitizen friendly

A slim, fully typed, asynchronous dependency injection library for achieving IoC.

TODO: Fill out this long description.

Table of Contents

Install

npm install @squirly/di

Usage

Container

import {Binding, Container, Injectable} from '@squirly/di';

const AuthenticationKey = Binding<string>('AuthenticationKey');
interface Fetcher {
  fetch: () => Promise<{data: string}>;
}
const Fetcher = Binding<Fetcher>('Fetcher');

@Injectable
class Client {
  static Tag = Binding.Tag<Client>('Client');
  static Inject = Injectable.Resolution(Fetcher);

  constructor(private readonly fetcher: Fetcher) {}

  getData(): Promise<string> {
    return this.fetcher
      .fetch()
      .then(result => `Received result: '${result.data}'`);
  }
}

async function fetcherFactory(c: Container<string>): Promise<Fetcher> {
  const key = await c.resolve(AuthenticationKey);

  return {
    fetch: () =>
      Promise.resolve({
        data: `Called with AuthenticationKey "${key}"`,
      }),
  };
}

const container = Container.create()
  .bindConstant(AuthenticationKey, 'my-secret-key')
  .bindSingletonFactory(Fetcher, fetcherFactory)
  .bindService(Client, Client);

const clientResult = container.resolve(Client).then(client => client.getData());

// Logs 'Received result: Called with AuthenticationKey "my-secret-key"';
clientResult.then(console.log);

Module

Using the definitions above, a Module can be created.

import {Module} from '@squirly/di';

const module = Module.create(
  Container.create()
    .bindConstant(AuthenticationKey, 'my-secret-key')
    .bindSingletonFactory(Fetcher, fetcherFactory),
).export(Fetcher);

const moduleContainer = Container.create()
  .importModule(module)
  .bindService(Client, Client);

moduleContainer.resolve(Client).then(client => {
  client.getData(); // returns "Calling API with 'yek-terces-ym'"
});

// $ExpectError
const resolution = moduleContainer.resolve(AuthenticationKey);
// Type 'string' is not assignable to 'Fetcher | Client'

// Logs "MissingDependencyError('Could not find dependency bound to AuthenticationKey.')"
clientResult.catch(console.log);

Maintainers

Tyler Jones ~ @squirly

Contribute

PRs accepted. Commits must follow the Angular Commit Message Conventions.

If editing the README, please conform to the standard-readme specification.

License

MIT © 2018 Tyler David Jones

0.4.0

5 years ago

0.3.2

5 years ago

0.3.1

6 years ago

0.3.0

6 years ago

0.2.2

6 years ago

0.2.1

6 years ago

0.2.0

6 years ago

0.1.0

6 years ago

0.0.3

6 years ago

0.0.2

6 years ago

0.0.1

6 years ago