UNPKG

unleash-server

Version:

Unleash is an enterprise ready feature flag service. It provides different strategies for handling feature flags.

90 lines 3.54 kB
import NotFoundError from '../error/notfound-error.js'; import { StrategyCreatedEvent, StrategyDeletedEvent, StrategyDeprecatedEvent, StrategyReactivatedEvent, StrategyUpdatedEvent, } from '../types/index.js'; import strategySchema from './strategy-schema.js'; import { NameExistsError } from '../error/index.js'; class StrategyService { constructor({ strategyStore }, { getLogger }, eventService) { this.strategyStore = strategyStore; this.eventService = eventService; this.logger = getLogger('services/strategy-service.js'); } async getStrategies() { return this.strategyStore.getAll(); } async getStrategy(name) { return this.strategyStore.get(name); } async removeStrategy(strategyName, auditUser) { const strategy = await this.strategyStore.get(strategyName); await this._validateEditable(strategy); await this.strategyStore.delete(strategyName); await this.eventService.storeEvent(new StrategyDeletedEvent({ data: { name: strategyName, }, auditUser, })); } async deprecateStrategy(strategyName, auditUser) { if (await this.strategyStore.exists(strategyName)) { // Check existence await this.strategyStore.deprecateStrategy({ name: strategyName }); await this.eventService.storeEvent(new StrategyDeprecatedEvent({ data: { name: strategyName, }, auditUser, })); } else { throw new NotFoundError(`Could not find strategy with name ${strategyName}`); } } async reactivateStrategy(strategyName, auditUser) { await this.strategyStore.get(strategyName); // Check existence await this.strategyStore.reactivateStrategy({ name: strategyName }); await this.eventService.storeEvent(new StrategyReactivatedEvent({ data: { name: strategyName, }, auditUser, })); } async createStrategy(value, auditUser) { const strategy = await strategySchema.validateAsync(value); strategy.deprecated = false; await this._validateStrategyName(strategy); await this.strategyStore.createStrategy(strategy); await this.eventService.storeEvent(new StrategyCreatedEvent({ data: strategy, auditUser, })); return this.strategyStore.get(strategy.name); } async updateStrategy(input, auditUser) { const value = await strategySchema.validateAsync(input); const strategy = await this.strategyStore.get(input.name); await this._validateEditable(strategy); await this.strategyStore.updateStrategy(value); await this.eventService.storeEvent(new StrategyUpdatedEvent({ data: value, auditUser, })); } _validateStrategyName(data) { return new Promise((resolve, reject) => { this.strategyStore .get(data.name) .then(() => reject(new NameExistsError(`Strategy with name ${data.name} already exist!`))) .catch(() => resolve(data)); }); } // This check belongs in the store. _validateEditable(strategy) { if (!strategy?.editable) { throw new Error(`Cannot edit strategy ${strategy?.name}`); } } } export default StrategyService; //# sourceMappingURL=strategy-service.js.map