Skip to content

Commit

Permalink
feat(core): Allow Plugin entities to be defined with a function
Browse files Browse the repository at this point in the history
Closes #906
  • Loading branch information
michaelbromley committed Jun 1, 2021
1 parent df98782 commit d130134
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 2 deletions.
5 changes: 4 additions & 1 deletion packages/core/src/plugin/plugin-metadata.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,10 @@ export function getEntitiesFromPlugins(plugins?: Array<Type<any> | DynamicModule
}
return plugins
.map(p => reflectMetadata(p, PLUGIN_METADATA.ENTITIES))
.reduce((all, entities) => [...all, ...(entities || [])], []);
.reduce((all, entities) => {
const resolvedEntities = typeof entities === 'function' ? entities() : entities ?? [];
return [...all, ...resolvedEntities];
}, []);
}

export function getModuleMetadata(module: Type<any>) {
Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/plugin/vendure-plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ export interface VendurePluginMetadata extends ModuleMetadata {
* @description
* The plugin may define custom [TypeORM database entities](https://typeorm.io/#/entities).
*/
entities?: Array<Type<any>>;
entities?: Array<Type<any>> | (() => Array<Type<any>>);
}
/**
* @description
Expand Down
37 changes: 37 additions & 0 deletions packages/dev-server/test-plugins/dynamic-entities-plugin.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
// product-review.entity.ts
import { DeepPartial } from '@vendure/common/lib/shared-types';
import { VendureEntity, VendurePlugin } from '@vendure/core';
import { Column, Entity } from 'typeorm';

@Entity()
export class TestEntityA extends VendureEntity {
constructor(input?: DeepPartial<TestEntityA>) {
super(input);
}

@Column()
textA: string;
}

@Entity()
export class TestEntityB extends VendureEntity {
constructor(input?: DeepPartial<TestEntityA>) {
super(input);
}

@Column()
textB: string;
}

@VendurePlugin({
entities: () => {
return DynamicEntitiesPlugin.useEntity === 'A' ? [TestEntityA] : [TestEntityB];
},
})
export class DynamicEntitiesPlugin {
static useEntity: 'A' | 'B';
static init(options: { useEntity: 'A' | 'B' }) {
this.useEntity = options.useEntity;
return this;
}
}

0 comments on commit d130134

Please sign in to comment.