Created
August 20, 2021 11:41
-
-
Save ernestofreyreg/479b9020376e6ccca4ee34314e238f01 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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