mardi 10 janvier 2017

Implementing C#'s using in JavaScript

I have many functions like that:

async function getUser(username: string) {
    var db = await connect();

    try {
        var result: User[] = await db.collection("users").find({"username": username}).toArray();
        return result.length > 0 ? result[0] : null;
    }
    finally {
        await db.close();
    }
}

and connect() function looks like that:

async function connect(): Promise<Db> {
    return await MongoClient.connect("connection string");
}

I want to avoid using the try/finally, connect() and close() in every function. I would like to have a magic, like the using statement is C#:

async function getUser(username: string) {
    using(var db = new MongoClient()) {
        var result: User[] = await db.collection("users").find({"username": username}).toArray();
        return result.length > 0 ? result[0] : null;
    }
}

How can I eliminate this code duplication?

Notice that I can use any TypeScript or ECMAScript6+ solution as well as any new feature that I need to install in order to use.

Although, a simple JavaScript solution using DI or any other design pattern would be great too.

Aucun commentaire:

Enregistrer un commentaire