From c9366427e811dfd0e615c8988245ccdc284e1d80 Mon Sep 17 00:00:00 2001 From: Pier-Luc Gendreau Date: Fri, 20 Nov 2020 23:00:39 -0500 Subject: [PATCH 1/2] Update with-mongodb to be TypeScript-friendly I slightly modified the approach so TypeScript can correctly infer types without actually having to type anything but the global: **index.d.ts** ```ts import { Db, MongoClient } from "mongodb"; declare global { namespace NodeJS { interface Global { mongoCache: { conn: { client: MongoClient | null; db: Db | null; } promise: Promise | null; }; } } } ``` --- examples/with-mongodb/util/mongodb.js | 15 ++++++--------- 1 file changed, 6 insertions(+), 9 deletions(-) diff --git a/examples/with-mongodb/util/mongodb.js b/examples/with-mongodb/util/mongodb.js index 4f0371eddde6a..461aa39959685 100644 --- a/examples/with-mongodb/util/mongodb.js +++ b/examples/with-mongodb/util/mongodb.js @@ -20,26 +20,23 @@ if (!MONGODB_DB) { * during API Route usage. */ let cached = global.mongo -if (!cached) cached = global.mongo = {} +if (!cached) cached = global.mongo = { conn: null, promise: null } export async function connectToDatabase() { if (cached.conn) return cached.conn if (!cached.promise) { - const conn = {} const opts = { useNewUrlParser: true, useUnifiedTopology: true, } cached.promise = MongoClient.connect(MONGODB_URI, opts) .then((client) => { - conn.client = client - return client.db(MONGODB_DB) - }) - .then((db) => { - conn.db = db - cached.conn = conn + return { + client, + db: client.db(MONGODB_DB), + } }) } - await cached.promise + cached.conn = await cached.promise return cached.conn } From 0fcbba53432eb1c7dd3e77f297aad347fabcc5f2 Mon Sep 17 00:00:00 2001 From: Pier-Luc Gendreau Date: Sat, 21 Nov 2020 13:40:31 -0500 Subject: [PATCH 2/2] lint --- examples/with-mongodb/util/mongodb.js | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/examples/with-mongodb/util/mongodb.js b/examples/with-mongodb/util/mongodb.js index 461aa39959685..59b7c16db2161 100644 --- a/examples/with-mongodb/util/mongodb.js +++ b/examples/with-mongodb/util/mongodb.js @@ -29,13 +29,13 @@ export async function connectToDatabase() { useNewUrlParser: true, useUnifiedTopology: true, } - cached.promise = MongoClient.connect(MONGODB_URI, opts) - .then((client) => { - return { - client, - db: client.db(MONGODB_DB), - } - }) + + cached.promise = MongoClient.connect(MONGODB_URI, opts).then((client) => { + return { + client, + db: client.db(MONGODB_DB), + } + }) } cached.conn = await cached.promise return cached.conn