| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152 |
- // src/configuration.ts
- import { App, Config, Configuration, Logger } from '@midwayjs/decorator';
- import path, { join } from 'path';
- import { ILifeCycle } from '@midwayjs/core';
- import { IMongooseApp, MongoDBConnect } from './connect/mongoDBConnect';
- import * as globby from 'globby';
- @Configuration({
- namespace: 'connect',
- importConfigs: [join(__dirname, 'config')],
- })
- export class AutoConfiguration implements ILifeCycle {
- @App()
- app: IMongooseApp;
- @Config('mongoose')
- mongoDBConfig;
- @Config('dbOptions')
- dbOptions;
- @Config('baseDir')
- baseDir: string;
- @Config('modelPath')
- modelPath: string;
- @Logger()
- logger;
- async onReady() {
- const connect = new MongoDBConnect(
- { dbOptions: this.dbOptions, ...this.mongoDBConfig },
- this.app
- ); //生成连接对像
- this.app.getApplicationContext().registerObject('mongooseDB', connect); //注册到app中
- this.loadModelFile(); //加载model文件
- }
- loadModelFile() {
- const modelPath = this.modelPath ? this.modelPath : 'app/model';
- const dir = path.join(this.baseDir, modelPath);
- const files: string[] = globby.sync(['**/*.(js|ts)', '!**/*.d.ts'], {
- cwd: dir,
- });
- files.forEach(filePath => require(path.join(dir, filePath))(this.app));
- }
- async onStop(): Promise<void> {
- // 关闭数据库连接
- await this.app.mongooseDB.closeDB();
- }
- }
|