BigW Consortium Gitlab

client.rb 1.34 KB
Newer Older
Kamil Trzcinski committed
1
module Mattermost
2
  ClientError = Class.new(Mattermost::Error)
3

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
    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

27 28 29 30
    def delete(session, path, options)
      json_response session.delete(path, options)
    end

31
    def session_get(path, options = {})
Kamil Trzcinski committed
32
      with_session do |session|
33
        get(session, path, options)
Kamil Trzcinski committed
34 35 36
      end
    end

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

43 44 45 46 47 48
    def session_delete(path, options = {})
      with_session do |session|
        delete(session, path, options)
      end
    end

Kamil Trzcinski committed
49 50 51
    def json_response(response)
      json_response = JSON.parse(response.body)

Kamil Trzcinski committed
52
      unless response.success?
53
        raise Mattermost::ClientError.new(json_response['message'] || 'Undefined error')
Kamil Trzcinski committed
54
      end
Kamil Trzcinski committed
55 56

      json_response
57
    rescue JSON::JSONError
58
      raise Mattermost::ClientError.new('Cannot parse response')
Kamil Trzcinski committed
59 60 61
    end
  end
end