|
|
@@ -1,6 +1,11 @@
|
|
|
import { IMidwayApplication } from '@midwayjs/core';
|
|
|
import { Inject } from '@midwayjs/decorator';
|
|
|
-import mongoose, { Connection, ConnectOptions, Mongoose } from 'mongoose';
|
|
|
+import mongoose, {
|
|
|
+ Connection,
|
|
|
+ ConnectOptions,
|
|
|
+ Mongoose,
|
|
|
+ Schema,
|
|
|
+} from 'mongoose';
|
|
|
|
|
|
export interface IMongooseApp extends IMidwayApplication {
|
|
|
mongoose: Mongoose;
|
|
|
@@ -13,6 +18,12 @@ export class MongoDBConnect {
|
|
|
|
|
|
private clients: Map<string, Connection>;
|
|
|
|
|
|
+ private dbOptions: ConnectOptions;
|
|
|
+
|
|
|
+ dynamicModels: { model: string; schema: Schema }[] = [];
|
|
|
+
|
|
|
+ subDomainMap: Map<string, { dbName: string; url: string }>;
|
|
|
+
|
|
|
private newConnection(
|
|
|
name = 'default',
|
|
|
config: { url: string; options: ConnectOptions }
|
|
|
@@ -38,15 +49,32 @@ export class MongoDBConnect {
|
|
|
}
|
|
|
}
|
|
|
|
|
|
+ private dynamicConnect(dbName: string, url: string) {
|
|
|
+ //连接新的数据库
|
|
|
+ const conn = mongoose.createConnection(`${url}/${dbName}`, this.dbOptions);
|
|
|
+ this.clients[dbName] = conn;
|
|
|
+ // 注册models
|
|
|
+ for (const dm of this.dynamicModels) {
|
|
|
+ conn.model(dm.model, dm.schema, dm.model);
|
|
|
+ }
|
|
|
+ return conn;
|
|
|
+ }
|
|
|
+
|
|
|
constructor(config: any, app: IMongooseApp) {
|
|
|
this.clients = new Map();
|
|
|
+ this.subDomainMap = new Map();
|
|
|
this.createClients(config);
|
|
|
+ this.dbOptions = config.dbOptions;
|
|
|
app.mongoose = mongoose;
|
|
|
app.mongooseDB = this;
|
|
|
}
|
|
|
|
|
|
- get(dbName: string) {
|
|
|
- return this.clients[dbName];
|
|
|
+ get(dbName: string, url?: string) {
|
|
|
+ const db = this.clients[dbName];
|
|
|
+ if (db) return db;
|
|
|
+
|
|
|
+ if (!url) throw new Error('数据库链接不能为空');
|
|
|
+ return this.dynamicConnect(dbName, url);
|
|
|
}
|
|
|
|
|
|
async closeDB() {
|