summaryrefslogtreecommitdiff
path: root/app/services/feature_flags/disable_service.rb
blob: 8a443ac1795058706003bfdd6e5163dd5d5434ee (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# frozen_string_literal: true

module FeatureFlags
  class DisableService < BaseService
    def execute
      return error('Feature Flag not found', 404) unless feature_flag_by_name
      return error('Feature Flag Scope not found', 404) unless feature_flag_scope_by_environment_scope
      return error('Strategy not found', 404) unless strategy_exist_in_persisted_data?

      ::FeatureFlags::UpdateService
        .new(project, current_user, update_params)
        .execute(feature_flag_by_name)
    end

    private

    def update_params
      if remaining_strategies.empty?
        params_to_destroy_scope
      else
        params_to_update_scope
      end
    end

    def remaining_strategies
      strong_memoize(:remaining_strategies) do
        feature_flag_scope_by_environment_scope.strategies.reject do |strategy|
          strategy['name'] == params[:strategy]['name'] &&
            strategy['parameters'] == params[:strategy]['parameters']
        end
      end
    end

    def strategy_exist_in_persisted_data?
      feature_flag_scope_by_environment_scope.strategies != remaining_strategies
    end

    def params_to_destroy_scope
      { scopes_attributes: [{ id: feature_flag_scope_by_environment_scope.id, _destroy: true }] }
    end

    def params_to_update_scope
      { scopes_attributes: [{ id: feature_flag_scope_by_environment_scope.id, strategies: remaining_strategies }] }
    end
  end
end