midwayjs typeorm 子组件模式加载实体问题

属于一个比较常见的问题,就是我们通过子组件提供orm 访问,以及api 处理,这样业务集成就会方便不少,比如UI/API 直接可以all-in-component

解决方法

解决方法实际很多,主要是我们在配置typeorm 的时候需要一个entities的信息,解决思路可以通过子组件暴露entity,然后宿主应用手工添加,还有就是使用entity 编译信息的绝对路径,还有一种就是使用midwayjs 的MidwayConfigService 直接修改对于typeorm 依赖的entity进行修改,以下主要说明MidwayConfigService 模式

参考玩法

  • entity 先暴露,这个比较简单,直接创建一个export entity 的ts 文件
import {User} from  "./user.entity"
export const entitys = [User]
  • 子组件使用MidwayConfigService 修改配置实体信息(核心是append)
import { Configuration,MidwayConfigService, Inject} from '@midwayjs/core';
import * as DefaultConfig from './config/config.default';
import {entitys} from "./entity"

@Configuration({
  namespace: 'user',
  importConfigs: [{ default: DefaultConfig }],
})


export class UserComponentConfiguration {

  @Inject()
  configService: MidwayConfigService;

  async onReady() {
    console.log('UserComponentConfiguration is ready');
    const config = this.configService.getConfiguration()
    // 通过configService 直接修改typeorm 的entities信息,这样就会进行扩展了
    config.typeorm.dataSource['default']['entities'].push(...entitys);
  }
}

说明

此方法实际来自官方的一个讨论,这样比较友好一些,而且不用修改宿主的信息,反而子组件暴露,宿主手工添加的模式比较费事,比如基于配置的简洁

参考资料

https://midwayjs.org/docs/extensions/orm

https://github.com/midwayjs/midway/discussions/3565

https://midwayjs.org/docs/built_in_service#midwayconfigservice

posted on 2025-12-05 08:00  荣锋亮  阅读(0)  评论(0)    收藏  举报

导航