configuration.ts 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  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('baseDir')
  17. baseDir: string;
  18. @Config('modelPath')
  19. modelPath: string;
  20. @Logger()
  21. logger;
  22. async onReady() {
  23. const connect = new MongoDBConnect(this.mongoDBConfig, this.app); //生成连接对像
  24. this.app.getApplicationContext().registerObject('mongooseDB', connect); //注册到app中
  25. this.loadModelFile(); //加载model文件
  26. }
  27. loadModelFile() {
  28. const modelPath = this.modelPath ? this.modelPath : 'app/model';
  29. const dir = path.join(this.baseDir, modelPath);
  30. const files: string[] = globby.sync(['**/*.(js|ts)', '!**/*.d.ts'], {
  31. cwd: dir,
  32. });
  33. files.forEach(filePath => require(path.join(dir, filePath))(this.app));
  34. }
  35. async onStop(): Promise<void> {
  36. // 关闭数据库连接
  37. await this.app.mongooseDB.closeDB();
  38. }
  39. }