From d130134b1e91aca5377a4eb86dc75b8c79fe5344 Mon Sep 17 00:00:00 2001 From: Michael Bromley Date: Tue, 1 Jun 2021 11:46:02 +0200 Subject: [PATCH] feat(core): Allow Plugin entities to be defined with a function Closes #906 --- packages/core/src/plugin/plugin-metadata.ts | 5 ++- packages/core/src/plugin/vendure-plugin.ts | 2 +- .../test-plugins/dynamic-entities-plugin.ts | 37 +++++++++++++++++++ 3 files changed, 42 insertions(+), 2 deletions(-) create mode 100644 packages/dev-server/test-plugins/dynamic-entities-plugin.ts diff --git a/packages/core/src/plugin/plugin-metadata.ts b/packages/core/src/plugin/plugin-metadata.ts index 4a9917cfd0..0537eea320 100644 --- a/packages/core/src/plugin/plugin-metadata.ts +++ b/packages/core/src/plugin/plugin-metadata.ts @@ -19,7 +19,10 @@ export function getEntitiesFromPlugins(plugins?: Array | 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) { diff --git a/packages/core/src/plugin/vendure-plugin.ts b/packages/core/src/plugin/vendure-plugin.ts index 5eca58eb99..31689c4e21 100644 --- a/packages/core/src/plugin/vendure-plugin.ts +++ b/packages/core/src/plugin/vendure-plugin.ts @@ -42,7 +42,7 @@ export interface VendurePluginMetadata extends ModuleMetadata { * @description * The plugin may define custom [TypeORM database entities](https://typeorm.io/#/entities). */ - entities?: Array>; + entities?: Array> | (() => Array>); } /** * @description diff --git a/packages/dev-server/test-plugins/dynamic-entities-plugin.ts b/packages/dev-server/test-plugins/dynamic-entities-plugin.ts new file mode 100644 index 0000000000..e5ce5570f8 --- /dev/null +++ b/packages/dev-server/test-plugins/dynamic-entities-plugin.ts @@ -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) { + super(input); + } + + @Column() + textA: string; +} + +@Entity() +export class TestEntityB extends VendureEntity { + constructor(input?: DeepPartial) { + 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; + } +}