M
M
Maxim Ivanov2017-09-11 14:41:56
Node.js
Maxim Ivanov, 2017-09-11 14:41:56

How to write an adequate DI in TypeScript for a Nodejs application?

You need something like this:
startup.ts

export class AppConfiguration {
    constructor() {

    }
}

@CreatableModule({
    services: [AppConfiguration]
})
export class StartupModule {

    constructor(public appConfig: AppConfiguration) {
        console.log(appConfig)
    }

    public f() {
        console.log(this.appConfig)
    }

}

But I can’t understand how Inject works like in Angular, I kind of started writing a decorator, but something doesn’t work to connect
startup.annotation.ts
export default class Injector {

    private static registry: {[key: string]: any} = {};

    static getRegistered(key: string): any {
        var registered = Injector.registry[key];
        if (registered) {
            return registered;
        } else {
            throw new Error(`Error: ${key} was not registered.`);
        }
    }

    static register(key: string, value: any) {
        var registered = Injector.registry[key];
        if (registered) {
            throw new Error(`Error: ${key} is already registered.`);
        }
        Injector.registry[key] = value;
    }
}

interface ICreatable<T> extends Function {
    new (): T;
    create: (...args) => T;
}

function CreatableModule(options) {
    return function (target) {

        options.services.forEach(service => {
            Injector.register(service.constructor.name, service)
        });

        console.log(options)
        console.log(target)
        target.create = (...args) => new target(...args);
        return target;
    }
}

main.ts
import {StartupModule} from "./app/Startup";

// правда не совсем понимаю как запускать в итоге этот модуль, чтобы он стартовал и у него уже были доступны внутри сервисы
new StartupModule();

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
RidgeA, 2017-09-11
@RidgeA

If it is necessary to use DI, and not write your own, then you can use https://github.com/mgechev/injection-js

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question