summaryrefslogtreecommitdiff
path: root/app/services/feature_flags/enable_service.rb
blob: b4cbb32e0037c2f77a503ec82f7b4572f87de222 (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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
# frozen_string_literal: true

module FeatureFlags
  class EnableService < BaseService
    def execute
      if feature_flag_by_name
        update_feature_flag
      else
        create_feature_flag
      end
    end

    private

    def create_feature_flag
      ::FeatureFlags::CreateService
        .new(project, current_user, create_params)
        .execute
    end

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

    def create_params
      if params[:environment_scope] == '*'
        params_to_create_flag_with_default_scope
      else
        params_to_create_flag_with_additional_scope
      end
    end

    def update_params
      if feature_flag_scope_by_environment_scope
        params_to_update_scope
      else
        params_to_create_scope
      end
    end

    def params_to_create_flag_with_default_scope
      {
        name: params[:name],
        scopes_attributes: [
          {
            active: true,
            environment_scope: '*',
            strategies: [params[:strategy]]
          }
        ]
      }
    end

    def params_to_create_flag_with_additional_scope
      {
        name: params[:name],
        scopes_attributes: [
          {
            active: false,
            environment_scope: '*'
          },
          {
            active: true,
            environment_scope: params[:environment_scope],
            strategies: [params[:strategy]]
          }
        ]
      }
    end

    def params_to_create_scope
      {
        scopes_attributes: [{
          active: true,
          environment_scope: params[:environment_scope],
          strategies: [params[:strategy]]
        }]
      }
    end

    def params_to_update_scope
      {
        scopes_attributes: [{
          id: feature_flag_scope_by_environment_scope.id,
          active: true,
          strategies: feature_flag_scope_by_environment_scope.strategies | [params[:strategy]]
        }]
      }
    end
  end
end