strapi/packages/strapi-database/lib/lifecycle-manager.js

36 lines
787 B
JavaScript
Raw Normal View History

2021-02-16 12:08:35 +01:00
'use strict';
const debug = require('debug')('strapi-database:lifecycle');
const { isFunction, isNil } = require('lodash/fp');
class LifecycleManager {
2021-02-17 15:51:47 +01:00
constructor() {
2021-02-16 12:08:35 +01:00
debug('Initialize lifecycle manager');
this.lifecycles = [];
}
register(lifecycle) {
debug('Register lifecycle');
this.lifecycles.push(lifecycle);
2021-02-17 15:51:47 +01:00
return this;
2021-02-16 12:08:35 +01:00
}
async run(action, model, ...args) {
for (const lifecycle of this.lifecycles) {
if (!isNil(lifecycle.model) && lifecycle.model !== model.uid) {
continue;
}
if (isFunction(lifecycle[action])) {
debug(`Run lifecycle ${action} for model ${model.uid}`);
await lifecycle[action](...args);
}
}
}
}
module.exports = strapi => {
return new LifecycleManager(strapi);
};