This commit is contained in:
pincman 2024-05-10 00:54:36 +08:00
commit e836f35165

View File

@ -0,0 +1,76 @@
/**
* MikroOrmModule.forFeature的entities配置
* @param modules
*/
export const resolveModuleEntities = (
modules: ModuleMetadata["imports"] = []
): MikroOrmModuleFeatureOptions[] =>
modules
// 获取所有模块的entities选项,组成[{entities: [PostEntity], contextName: 'xxx'},{entities: [PostEntity], contextName: 'fff'}],[{entities: [UserEntity]}]这样的形式
.map((m) => ("entities" in m && isFunction(m.entities) ? m.entities() : []))
// 合并所有entities选项,形成一维数组用于传入MikroOrmModule,如[{entities: [PostEntity], contextName: 'xxx'},{entities: [PostEntity], contextName: 'fff'},{entities: [UserEntity]}]
.reduce((o, n) => [...o, ...n], []);
/**
* MikroOrm使用的entities配置
* @param modules
*/
const resolveConfigEntities = (
modules: ModuleMetadata["imports"] = []
): EntityClass<Partial<any>>[] => {
const moduleEntities = resolveModuleEntities(modules);
return (
moduleEntities
.map(({ entities }) => entities)
// 把所有模块的entities合并到一个数组中
.reduce((o, n) => [...o, ...n], [])
// 过滤去重相同的entity
.reduce((o, n) => [...o.filter((c) => c !== n), n], [])
);
};
export type DatabaseModuleOptions = Omit<
MikroOrmModuleSyncOptions,
"entities"
> & {
modules?: ModuleMetadata["imports"];
};
@Module({
// imports: [MikroOrmModule.forFeature({ entities: [PostEntity] })],
controllers: [PostController],
providers: [PostService],
exports: [PostService],
})
export class ContentModule {
static entities(): MikroOrmModuleFeatureOptions[] {
return [{ entities: [PostEntity] }];
}
}
@Module({})
export class DatabaseModule {
static async forRoot(
options: DatabaseModuleOptions = {}
): Promise<DynamicModule> {
const entitiesImports = resolveModuleEntities(options.modules ?? []).map(
(es) => MikroOrmModule.forFeature(es)
);
return {
global: true,
module: DatabaseModule,
imports: [
...entitiesImports,
MikroOrmModule.forRootAsync({
useFactory: () =>
omit(
getDbConfigOptions<MikroOrmModuleSyncOptions>(options),
"entities"
),
}),
],
exports: [MikroOrmModule],
};
}
}