How use inversify to explain how build my class

51 views Asked by At

First sorry for my english. I'm a French with a poor english.

Hello every one i'm starting learn use clean architecture by writing an api in type script. So I want use dependency injection principe to isolate all my layers. I use inversify to do it but I'm in trouble with this use case. I have an DatabaseRepoitory which is interface that define a method to connect to my database and two kind of adapter that implement it.

/** My Database Adpater */

export interface DatabaseAdapter {
    connect(): Promise<void>;
}

/** My repository */

@injectable()
export class MongoDBDatabaseAdapter implements DatabaseAdapter {
    private client: MongoClient;

    constructor(private readonly url: string) {
        this.client = new MongoClient(url);
    }

    async connect(): Promise<void> {
        await this.client.connect();
    }
}
@injectable()
export class MysqlDatabaseAdapters implements DatabaseAdapter {

    private connection: Connection;

    constructor(
        private readonly host: string,
        private readonly port: number,
        private readonly username: string,
        private readonly password: string,
        private readonly database: string
    ){
        this.connection = createConnection({
            host: this.host,
            port: this.port,
            user: this.username,
            password: this.password,
            database: this.database
        });
    }

    connect(): Promise<void> {
        return new Promise((resolve, reject) => {
            this.connection.connect((error) => {
                if(error) {
                    reject(error);
                } else {
                    resolve();
                }
            });
        });
    }
}

Now it's time to me to define my inversify configuration to explain whats Adapter to use (to bind for DatabaseAdapter) and how build it (or instance it). But I don't know how do it properly. I learn things about Factory and I propose myself doing it by this way but i still not sure by the way I do it. Can anyone please help me to define how I must write my config.


/**
I think it's to verbose
*/
container.bind<interfaces.Factory<DatabaseAdapter>>("Factory<DatabaseAdapter>").toFactory<DatabaseAdapter>((context: interfaces.Context) => {
    return () => {
        return new MongoDBDatabaseAdapter(env.url);
    };
});

/**

//this don't work because they are no way to pass my url to my constructor

container.bind<DatabaseAdapter>(TYPES.DatabaseAdapter).to(MongoDBDatabaseAdapter);

//methode using factory


*/

0

There are 0 answers