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) {
let cached = global.mongo
if (!cached) {
cached = global.mongo = {}
cached = global.mongo = { conn: null, promise: null }
}
export async function connectToDatabase() {
......@@ -31,27 +31,18 @@ export async function connectToDatabase() {
}
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
})
cached.promise = MongoClient.connect(MONGODB_URI, opts).then((client) => {
return {
client,
db: client.db(MONGODB_DB),
}
})
}
await cached.promise
cached.conn = await cached.promise
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