configuration.ts 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. // src/configuration.ts
  2. import { App, Config, Configuration, Logger } from '@midwayjs/decorator';
  3. import path, { join } from 'path';
  4. import { ILifeCycle } from '@midwayjs/core';
  5. import { IMongooseApp, MongoDBConnect } from './connect/mongoDBConnect';
  6. import * as globby from 'globby';
  7. @Configuration({
  8. namespace: 'connect',
  9. importConfigs: [join(__dirname, 'config')],
  10. })
  11. export class AutoConfiguration implements ILifeCycle {
  12. @App()
  13. app: IMongooseApp;
  14. @Config('mongoose')
  15. mongoDBConfig;
  16. @Config('dbOptions')
  17. dbOptions;
  18. @Config('baseDir')
  19. baseDir: string;
  20. @Config('modelPath')
  21. modelPath: string;
  22. @Logger()
  23. logger;
  24. async onReady() {
  25. const connect = new MongoDBConnect(
  26. { dbOptions: this.dbOptions, ...this.mongoDBConfig },
  27. this.app
  28. ); //生成连接对像
  29. this.app.getApplicationContext().registerObject('mongooseDB', connect); //注册到app中
  30. this.loadModelFile(); //加载model文件
  31. }
  32. loadModelFile() {
  33. const modelPath = this.modelPath ? this.modelPath : 'app/model';
  34. const dir = path.join(this.baseDir, modelPath);
  35. const files: string[] = globby.sync(['**/*.(js|ts)', '!**/*.d.ts'], {
  36. cwd: dir,
  37. });
  38. files.forEach(filePath => require(path.join(dir, filePath))(this.app));
  39. }
  40. async onStop(): Promise<void> {
  41. // 关闭数据库连接
  42. await this.app.mongooseDB.closeDB();
  43. }
  44. }