@t2ee/core

Dependency injection and auto configuration, core component for the rest @t2ee projects.

Introduction

This projects aims to be foundation component for the rest of @t2ee projects. It provides dependency injection and auto configuration functionalities.

Installation

npm i reflect-metadata @t2ee/core -S

Usage

Basic Depedency Injection

import {
    Component,
} from '@t2ee/core';

@Component
class Mountable {
    message: string = 'hello world';
}
import {
    Component,
    AutoWired,
    Container,
} from '@t2ee/core';

@Component
class Main {
    @AutoWired mounted: Mountable;
}

const main = Container.get(Main);
console.log(main.mounted.message) // 'hello world';

Auto Configuration

//@Component can't have this
class Mountable {
    message: string = 'hello world';
}
@Configuration
class Config {
    @Bean mountable(): Mountable {
        const mountable = new Mountable();
        mountable.message = 'hello';
        return mountable;
    }
    @Bean('mount') stringMountable(): Mountable {
        const mountable = new Mountable();
        mountable.message = `I'm different`;
        return mountable;
    }
}
@Component
class Main {
    @AutoWired mounted: Mountable;
    @AutoWired('mount') another: Mountable;
}
const main = Container.get(Main);
console.log(main.mounted.message) // 'hello'
console.log(main.another.message) // 'I\'m different'

Load configuration file and Inject

application.yaml

server:
    port: 8080
ConfigurationStore.loadFile(path.resolve(__dirname, 'application'));
@Component
class Main {
    @Value('server.port') port: number;
}

OR

@EnableConfiguration('application')
//or @EnableConfiguration(() => 'application')
@Component
class Main {
    @Value('server.port') port: number;
}

Function and Variables in configuration file

level: LogLevel.DEBUG
port: random(100)
import {
    ConfigurationStore,
} from '@t2ee/core';
ConfigurationStore.provide('LogLevel', LogLevel);
ConfigurationStore.provide('random', (value) => Math.ceil(Math.random() * value));

Implement Custom Provider

example scenario: extrating information from process

function Process(name: string) {
    return (target: Object, key: string) => {
        return AutoWired('process-information', { name });
    };
}
class MyProvider implements Provider {
    resolve<T extends Object>(value: T, meta: AutoWireMeta, args: any[]) {
        if (meta.type === 'process-information') {
            const { name } = meta.data;
            return process.env[name];
        }
    }
}
Container.inject('process-information', new MyProvider());
@Component
class Main {
    @Process('USER')
    systemUser: string;
}

API

Coming soon …

Coming soon…