Unverified Commit e6c35185 authored by Pier-Luc Gendreau's avatar Pier-Luc Gendreau Committed by GitHub

Update with-mongodb to be TypeScript-friendly (#19383)

* 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<MongoClient> | null;
      };
    }
  }
}
```

* lint
Co-authored-by: 's avatarJoe Haddad <joe.haddad@zeit.co>
parent 9553b6da
...@@ -22,7 +22,7 @@ if (!MONGODB_DB) { ...@@ -22,7 +22,7 @@ if (!MONGODB_DB) {
let cached = global.mongo let cached = global.mongo
if (!cached) { if (!cached) {
cached = global.mongo = {} cached = global.mongo = { conn: null, promise: null }
} }
export async function connectToDatabase() { export async function connectToDatabase() {
...@@ -31,27 +31,18 @@ export async function connectToDatabase() { ...@@ -31,27 +31,18 @@ export async function connectToDatabase() {
} }
if (!cached.promise) { if (!cached.promise) {
const conn = {}
const opts = { const opts = {
useNewUrlParser: true, useNewUrlParser: true,
useUnifiedTopology: true, useUnifiedTopology: true,
} }
cached.promise = MongoClient.connect(MONGODB_URI, opts) cached.promise = MongoClient.connect(MONGODB_URI, opts).then((client) => {
.then((client) => { return {
conn.client = client client,
db: client.db(MONGODB_DB),
return client.db(MONGODB_DB) }
}) })
.then((db) => {
conn.db = db
cached.conn = conn
})
} }
cached.conn = await cached.promise
await cached.promise
return cached.conn return cached.conn
} }
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment