BigW Consortium Gitlab

client.rb 1.11 KB
Newer Older
Kamil Trzcinski committed
1
module Mattermost
2 3
  class ClientError < Mattermost::Error; end

Kamil Trzcinski committed
4 5 6 7 8 9 10 11
  class Client
    attr_reader :user

    def initialize(user)
      @user = user
    end

    def with_session(&blk)
12
      Mattermost::Session.new(user).with_session(&blk)
Kamil Trzcinski committed
13 14
    end

15 16 17 18 19 20 21 22 23 24 25 26 27
    private

    # Should be used in a session manually
    def get(session, path, options = {})
      json_response session.get(path, options)
    end

    # Should be used in a session manually
    def post(session, path, options = {})
      json_response session.post(path, options)
    end

    def session_get(path, options = {})
Kamil Trzcinski committed
28
      with_session do |session|
29
        get(session, path, options)  
Kamil Trzcinski committed
30 31 32
      end
    end

33
    def session_post(path, options = {})
Kamil Trzcinski committed
34
      with_session do |session|
35
        post(session, path, options)
Kamil Trzcinski committed
36 37 38 39 40 41
      end
    end

    def json_response(response)
      json_response = JSON.parse(response.body)

Kamil Trzcinski committed
42
      unless response.success?
43
        raise Mattermost::ClientError.new(json_response['message'] || 'Undefined error')
Kamil Trzcinski committed
44
      end
Kamil Trzcinski committed
45 46

      json_response
47
    rescue JSON::JSONError
48
      raise Mattermost::ClientError.new('Cannot parse response')
Kamil Trzcinski committed
49 50 51
    end
  end
end