Browse Source

feat(core): Allow Plugin entities to be defined with a function

Closes #906
Michael Bromley 4 years ago
parent
commit
d130134b1e

+ 4 - 1
packages/core/src/plugin/plugin-metadata.ts

@@ -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>) {

+ 1 - 1
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<Type<any>>;
+    entities?: Array<Type<any>> | (() => Array<Type<any>>);
 }
 /**
  * @description

+ 37 - 0
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<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;
+    }
+}