Skip to content

Instantly share code, notes, and snippets.

@ernestofreyreg
Created August 20, 2021 11:41
Show Gist options
  • Save ernestofreyreg/479b9020376e6ccca4ee34314e238f01 to your computer and use it in GitHub Desktop.
Save ernestofreyreg/479b9020376e6ccca4ee34314e238f01 to your computer and use it in GitHub Desktop.
import { Db, MongoClient, MongoClientOptions } from 'mongodb'
const MONGODB_URI = process.env.MONGO_DB_URL
const MONGODB_DB = process.env.MONGO_DB_NAME
let cached = global.mongo
if (!cached) {
cached = global.mongo = { conn: null, promise: null }
}
const connectToDatabase = async (): Promise<{ client: MongoClient; db: Db }> => {
if (cached.conn) {
return cached.conn
}
if (!cached.promise) {
const opts: MongoClientOptions = {}
cached.promise = MongoClient.connect(MONGODB_URI, opts).then(client => {
return {
client,
db: client.db(MONGODB_DB)
}
})
}
cached.conn = await cached.promise
return cached.conn
}
export async function withMongo<T>(fn: (db: Db) => Promise<T>): Promise<T> {
const conn = await connectToDatabase()
return await fn(conn.db)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment