ChatGPT-Next-Web/app/db/mongdb.ts
2023-04-14 14:06:01 +08:00

36 lines
1.1 KiB
TypeScript

import { MongoClient } from "mongodb";
const uri = process.env.MONGODB_URI as string; // your mongodb connection string
const options = {};
declare global {
var _mongoClientPromise: Promise<MongoClient>;
}
class Singleton {
private static _instance: Singleton;
private client: MongoClient;
private clientPromise: Promise<MongoClient>;
private constructor() {
this.client = new MongoClient(uri, options);
this.clientPromise = this.client.connect();
if (process.env.NODE_ENV === "development") {
// In development mode, use a global variable so that the value
// is preserved across module reloads caused by HMR (Hot Module Replacement).
global._mongoClientPromise = this.clientPromise;
}
}
public static get instance() {
if (!this._instance) {
this._instance = new Singleton();
}
return this._instance.clientPromise;
}
}
const clientPromise = Singleton.instance;
// Export a module-scoped MongoClient promise. By doing this in a
// separate module, the client can be shared across functions.
export default clientPromise;