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

Kamil Trzcinski's avatar
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)
Kamil Trzcinski's avatar
Kamil Trzcinski committed
12
      Mattermost::Session.new(user).with_session(&blk)
Kamil Trzcinski's avatar
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's avatar
Kamil Trzcinski committed
28
      with_session do |session|
29
        get(session, path, options)
Kamil Trzcinski's avatar
Kamil Trzcinski committed
30 31 32
      end
    end

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

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

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

      json_response
Z.J. van de Weg's avatar
Z.J. van de Weg committed
47
    rescue JSON::JSONError
Kamil Trzcinski's avatar
Kamil Trzcinski committed
48
      raise Mattermost::ClientError.new('Cannot parse response')
Kamil Trzcinski's avatar
Kamil Trzcinski committed
49 50 51
    end
  end
end