BigW Consortium Gitlab

features.rb 1.8 KB
Newer Older
1 2 3 4
module API
  class Features < Grape::API
    before { authenticated_as_admin! }

5 6 7 8 9 10 11 12 13 14 15 16
    helpers do
      def gate_value(params)
        case params[:value]
        when 'true'
          true
        when '0', 'false'
          false
        else
          params[:value].to_i
        end
      end

17 18 19 20 21 22
      def gate_targets(params)
        targets = []
        targets << Feature.group(params[:feature_group]) if params[:feature_group]
        targets << User.find_by_username(params[:user]) if params[:user]

        targets
23 24 25
      end
    end

26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
    resource :features do
      desc 'Get a list of all features' do
        success Entities::Feature
      end
      get do
        features = Feature.all

        present features, with: Entities::Feature, current_user: current_user
      end

      desc 'Set the gate value for the given feature' do
        success Entities::Feature
      end
      params do
        requires :value, type: String, desc: '`true` or `false` to enable/disable, an integer for percentage of time'
41
        optional :feature_group, type: String, desc: 'A Feature group name'
42
        optional :user, type: String, desc: 'A GitLab username'
43 44 45
      end
      post ':name' do
        feature = Feature.get(params[:name])
46
        targets = gate_targets(params)
47
        value = gate_value(params)
48

49 50
        case value
        when true
51 52 53 54 55
          if targets.present?
            targets.each { |target| feature.enable(target) }
          else
            feature.enable
          end
56
        when false
57 58 59 60 61
          if targets.present?
            targets.each { |target| feature.disable(target) }
          else
            feature.disable
          end
62
        else
63
          feature.enable_percentage_of_time(value)
64 65 66 67 68 69 70
        end

        present feature, with: Entities::Feature, current_user: current_user
      end
    end
  end
end