midwayjs / midway

🍔 A Node.js Serverless Framework for front-end/full-stack developers. Build the application for next decade. Works on AWS, Alibaba Cloud, Tencent Cloud and traditional VM/Container. Super easy integrate with React and Vue. 🌈
https://www.midwayjs.org/
MIT License
7.4k stars 576 forks source link

@midwayjs/orm 动态设置数据库链接配置 #1377

Closed xiaoqianghaochi closed 2 years ago

xiaoqianghaochi commented 2 years ago

在configuration.ts添加orm,但orm的配置需要从服务器获取,不是在config.default.ts中写死的,导致数据库链接失败,有什么方式可以解决,钩子等?

czy88840616 commented 2 years ago

可以用onConfigLoad生命周期动态获取配置,具体查看文档。

xiaoqianghaochi commented 2 years ago

1、@midwayjs/orm的配置在configuration.ts引入如下

import { ILifeCycle, IMidwayContainer } from '@midwayjs/core';
import { App, Configuration, Inject, Init } from '@midwayjs/decorator';
import { Application } from 'egg';
import { join } from 'path';
// eslint-disable-next-line node/no-unpublished-import
import 'tsconfig-paths/register';
const staticCache = require('koa-static-cache');
import { ConfService } from '@/service/conf';

import * as orm from '@midwayjs/orm';
@Configuration({
  imports: [orm],
  importConfigs: [join(__dirname, './config')],
  conflictCheck: true,
})
export class ContainerLifeCycle implements ILifeCycle {
  @App()
  app: Application;

  **_async onConfigLoad(container: IMidwayContainer) {
    const remoteConfigService = await container.getAsync(ConfService);
    const remoteConfig = await remoteConfigService.getData();
    console.log('remoteConfig==', remoteConfig);
    return {
      data: remoteConfig,
    };
  }_**

  async onReady() {
    this.app.use(
      staticCache({
        prefix: '/static/',
        dir: join(this.app.getAppDir(), 'www/static/'),
      })
    );
  }
}
`
2、config.default.ts的配置
`
import { EggAppConfig, EggAppInfo, PowerPartial } from 'egg';
import { join } from 'path';

export type DefaultConfig = PowerPartial<EggAppConfig>;

// history模式
export const historyApiFallback = {
  // disableDotRule: false,
};

export default (appInfo: EggAppInfo) => {
  ...
};

// typeorm 配置
export const orm = {
  type: 'mysql',
  synchronize: true,
  logging: false,
  host: '10.*.*.*',
  port: '3306',
  username: 'username',
  password: 'password',
  persistent: '1',
  database: 'database',
};

3、按照官网文档在onConfigLoad中获取远程配置,并没有动态改变orm的配置,且文档说明有【注意,onConfigLoad 生命周期会在 egg 插件(若有)初始化之后执行,所以不能用于覆盖 egg 插件所使用的配置。】

czy88840616 commented 2 years ago

你的key 没对上吧,你返回的是 {data: xxx},orm配置是 {orm: xxx}

xiaoqianghaochi commented 2 years ago

好的,我试一试可以了,多谢