Skip to content

Commit

Permalink
Update with-mongodb to be TypeScript-friendly
Browse files Browse the repository at this point in the history
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<MongoClient> | null;
      };
    }
  }
}
```
  • Loading branch information
Zertz authored Nov 21, 2020
1 parent b28b8b2 commit c936642
Showing 1 changed file with 6 additions and 9 deletions.
15 changes: 6 additions & 9 deletions examples/with-mongodb/util/mongodb.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
}

0 comments on commit c936642

Please sign in to comment.