@backstage/backend-defaults
Version:
Backend defaults used by Backstage backend apps
89 lines (85 loc) • 2.55 kB
JavaScript
;
var backendPluginApi = require('@backstage/backend-plugin-api');
class BackendPluginLifecycleImpl {
constructor(logger, pluginMetadata) {
this.logger = logger;
this.pluginMetadata = pluginMetadata;
}
#hasStarted = false;
#hasShutdown = false;
#startupTasks = [];
#shutdownTasks = [];
addStartupHook(hook, options) {
if (this.#hasStarted) {
throw new Error("Attempted to add startup hook after startup");
}
this.#startupTasks.push({ hook, options });
}
async startup() {
if (this.#hasStarted) {
return;
}
this.#hasStarted = true;
this.logger.debug(
`Running ${this.#startupTasks.length} plugin startup tasks...`
);
await Promise.all(
this.#startupTasks.map(async ({ hook, options }) => {
const logger = options?.logger ?? this.logger;
try {
await hook();
logger.debug(`Plugin startup hook succeeded`);
} catch (error) {
logger.error(`Plugin startup hook failed, ${error}`);
}
})
);
}
addShutdownHook(hook, options) {
if (this.#hasShutdown) {
throw new Error("Attempted to add shutdown hook after shutdown");
}
const plugin = this.pluginMetadata.getId();
const logger = options?.logger?.child({ plugin }) ?? this.logger;
this.#shutdownTasks.push({
hook,
options: {
...options,
logger
}
});
}
async shutdown() {
if (this.#hasShutdown) {
return;
}
this.#hasShutdown = true;
this.logger.debug(
`Running ${this.#shutdownTasks.length} plugin shutdown tasks...`
);
await Promise.all(
this.#shutdownTasks.map(async ({ hook, options }) => {
const logger = options?.logger ?? this.logger;
try {
await hook();
logger.debug(`Plugin shutdown hook succeeded`);
} catch (error) {
logger.error("Plugin shutdown hook failed", error);
}
})
);
}
}
const lifecycleServiceFactory = backendPluginApi.createServiceFactory({
service: backendPluginApi.coreServices.lifecycle,
deps: {
logger: backendPluginApi.coreServices.logger,
pluginMetadata: backendPluginApi.coreServices.pluginMetadata
},
async factory({ logger, pluginMetadata }) {
return new BackendPluginLifecycleImpl(logger, pluginMetadata);
}
});
exports.BackendPluginLifecycleImpl = BackendPluginLifecycleImpl;
exports.lifecycleServiceFactory = lifecycleServiceFactory;
//# sourceMappingURL=lifecycleServiceFactory.cjs.js.map