I've been working on integrating a MongoDB database with the Next.js built-in API by using the code snippet below, which I found online.
/api/blogs/[slug].ts
import type { NextApiRequest, NextApiResponse } from 'next'
import { connectToDatabase } from '../../../database/connectToDatabase'
const allowedReqMethod = "GET"
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
if (req.method === allowedReqMethod) {
const slug = req.query.slug
try{
const {db} = await connectToDatabase()
const blog = await db.collection("blogs").findOne({slug})
res.status(200).json({blog})
} catch (error) {
res.status(500).json({ message: "Internal server error" })
}
} else {
res.status(400).json({ message: "Bad request" })
}
}
connectToDatabase.ts
import { Db, MongoClient } from "mongodb";
const MONGODB_URI = process.env.MONGODB_URI;
const MONGODB_DB = process.env.MONGODB_DB;
let cachedClient: MongoClient;
let cachedDb: Db;
export async function connectToDatabase() {
// check the cached.
if (cachedClient && cachedDb) {
// load from cache
return {
client: cachedClient,
db: cachedDb,
};
}
// set the connection options
const opts = {
useNewUrlParser: true,
useUnifiedTopology: true,
};
// check the MongoDB URI
if (!MONGODB_URI) {
throw new Error("Define the MONGODB_URI environmental variable");
}
// check the MongoDB DB
if (!MONGODB_DB) {
throw new Error("Define the MONGODB_DB environmental variable");
}
// Connect to cluster
let client = new MongoClient(MONGODB_URI);
await client.connect();
let db = client.db(MONGODB_DB);
// set cache
cachedClient = client;
cachedDb = db;
return {
client: cachedClient,
db: cachedDb,
};
}
I'm wondering if the API establishes a new database connection (using the connectToDatabase() function) every time it's called. If so, wouldn't this be considered poor practice due to potential delays?