mongoDBConnect.ts 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. import { IMidwayApplication } from '@midwayjs/core';
  2. import { Inject } from '@midwayjs/decorator';
  3. import mongoose, { Connection, ConnectOptions, Mongoose } from 'mongoose';
  4. export interface IMongooseApp extends IMidwayApplication {
  5. mongoose: Mongoose;
  6. mongooseDB: MongoDBConnect;
  7. }
  8. export class MongoDBConnect {
  9. @Inject()
  10. logger;
  11. private clients: Map<string, Connection>;
  12. private newConnection(
  13. name = 'default',
  14. config: { url: string; options: ConnectOptions }
  15. ) {
  16. const { url, options } = config;
  17. if (!url) {
  18. return this.logger.error('url 不能为空!');
  19. }
  20. const conn = mongoose.createConnection(url, options);
  21. this.clients[name] = conn;
  22. }
  23. private createClients(config: any) {
  24. const { client, clients } = config;
  25. if (client) {
  26. this.newConnection(client.name, client);
  27. }
  28. if (clients) {
  29. Object.keys(clients).forEach(dbName =>
  30. this.newConnection(dbName, clients[dbName])
  31. );
  32. }
  33. }
  34. constructor(config: any, app: IMongooseApp) {
  35. this.clients = new Map();
  36. this.createClients(config);
  37. app.mongoose = mongoose;
  38. app.mongooseDB = this;
  39. }
  40. get(dbName: string) {
  41. return this.clients[dbName];
  42. }
  43. async closeDB() {
  44. const connects: Connection[] = Object.values(this.clients);
  45. for (const connect of connects) {
  46. await connect.close();
  47. }
  48. }
  49. }