diff --git a/packages/strapi-database/lib/__tests__/lifecycle-manager.test.js b/packages/strapi-database/lib/__tests__/lifecycle-manager.test.js new file mode 100644 index 0000000000..a0c3d3291c --- /dev/null +++ b/packages/strapi-database/lib/__tests__/lifecycle-manager.test.js @@ -0,0 +1,54 @@ +'use strict'; + +const createLifecycleManager = require('../lifecycle-manager'); + +describe('Lifecycle Manager', () => { + test('Allows registering lifecycles', () => { + const manager = createLifecycleManager(); + + const lifecycle = {}; + manager.register(lifecycle); + + expect(manager.lifecycles).toEqual([lifecycle]); + }); + + test('Will run all the lifecycles if no model specified', async () => { + const lifecycleA = { + find: jest.fn(), + }; + + const lifecycleB = { + find: jest.fn(), + }; + + const manager = createLifecycleManager(); + + manager.register(lifecycleA).register(lifecycleB); + + await manager.run('find', { uid: 'test-uid' }); + + expect(lifecycleA.find).toHaveBeenCalled(); + expect(lifecycleB.find).toHaveBeenCalled(); + }); + + test('Will match on model if specified', async () => { + const lifecycleA = { + model: 'test-uid', + find: jest.fn(), + }; + + const lifecycleB = { + model: 'other-uid', + find: jest.fn(), + }; + + const manager = createLifecycleManager(); + + manager.register(lifecycleA).register(lifecycleB); + + await manager.run('find', { uid: 'test-uid' }); + + expect(lifecycleA.find).toHaveBeenCalled(); + expect(lifecycleB.find).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/strapi-database/lib/database-manager.js b/packages/strapi-database/lib/database-manager.js index f777de90c1..f610c22374 100644 --- a/packages/strapi-database/lib/database-manager.js +++ b/packages/strapi-database/lib/database-manager.js @@ -24,7 +24,7 @@ class DatabaseManager { this.models = new Map(); this.migrations = createMigrationManager(this); - this.lifecycles = createLifecycleManager(this); + this.lifecycles = createLifecycleManager(); } async initialize() { diff --git a/packages/strapi-database/lib/lifecycle-manager.js b/packages/strapi-database/lib/lifecycle-manager.js index 094a234aa2..2781618633 100644 --- a/packages/strapi-database/lib/lifecycle-manager.js +++ b/packages/strapi-database/lib/lifecycle-manager.js @@ -3,9 +3,8 @@ const debug = require('debug')('strapi-database:lifecycle'); const { isFunction, isNil } = require('lodash/fp'); class LifecycleManager { - constructor(db) { + constructor() { debug('Initialize lifecycle manager'); - this.db = db; this.lifecycles = []; } @@ -13,6 +12,7 @@ class LifecycleManager { debug('Register lifecycle'); this.lifecycles.push(lifecycle); + return this; } async run(action, model, ...args) {