diff --git a/packages/repository/src/__tests__/unit/mixins/repository.mixin.unit.ts b/packages/repository/src/__tests__/unit/mixins/repository.mixin.unit.ts index 05ee94b7cf0e..73bbad9a1486 100644 --- a/packages/repository/src/__tests__/unit/mixins/repository.mixin.unit.ts +++ b/packages/repository/src/__tests__/unit/mixins/repository.mixin.unit.ts @@ -11,6 +11,7 @@ import { DefaultCrudRepository, Entity, juggler, + Model, ModelDefinition, Repository, RepositoryMixin, @@ -77,6 +78,23 @@ describe('RepositoryMixin', () => { expectNoteRepoToBeBound(myApp); }); + it('binds user defined component with models', () => { + @model() + class MyModel extends Model {} + + class MyModelComponent { + models = [MyModel]; + } + + const myApp = new AppWithRepoMixin(); + myApp.component(MyModelComponent); + + const boundModels = myApp.find('models.*').map(b => b.key); + expect(boundModels).to.containEql('models.MyModel'); + const modelCtor = myApp.getSync('models.MyModel'); + expect(modelCtor).to.be.equal(MyModel); + }); + context('migrateSchema', () => { let app: AppWithRepoMixin; let migrateStub: sinon.SinonStub; diff --git a/packages/repository/src/mixins/repository.mixin.ts b/packages/repository/src/mixins/repository.mixin.ts index 3c9fce1fc079..ab71bf033e73 100644 --- a/packages/repository/src/mixins/repository.mixin.ts +++ b/packages/repository/src/mixins/repository.mixin.ts @@ -189,7 +189,9 @@ export function RepositoryMixin>( nameOrOptions?: string | BindingFromClassOptions, ) { const binding = super.component(componentCtor, nameOrOptions); - this.mountComponentRepositories(componentCtor); + const instance = this.getComponentInstance(componentCtor); + this.mountComponentRepositories(instance); + this.mountComponentModels(instance); return binding; } @@ -200,11 +202,16 @@ export function RepositoryMixin>( * * @param component - The component to mount repositories of */ - mountComponentRepositories(component: Class) { - const componentKey = `${CoreBindings.COMPONENTS}.${component.name}`; - const compInstance = this.getSync<{ - repositories?: Class>[]; - }>(componentKey); + mountComponentRepositories( + component: Class | {repositories?: Class>[]}, + ) { + // accept also component class to preserve backwards compatibility + const compInstance = + typeof component === 'function' + ? this.getComponentInstance<{ + repositories?: Class>[]; + }>(component) + : component; if (compInstance.repositories) { for (const repo of compInstance.repositories) { @@ -213,6 +220,18 @@ export function RepositoryMixin>( } } + mountComponentModels(component: {models?: Class[]}) { + if (!component.models) return; + for (const m of component.models) { + this.model(m); + } + } + + getComponentInstance(component: Class) { + const componentKey = `${CoreBindings.COMPONENTS}.${component.name}`; + return this.getSync(componentKey); + } + /** * Update or recreate the database schema for all repositories. *