Completed
Push — master ( b24959...b63c86 )
by John
01:57
created

Client.post()   B

Complexity

Conditions 6

Size

Total Lines 20

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
c 0
b 0
f 0
dl 0
loc 20
rs 8
1
module MediumSdk
2
  class Client
3
    attr_accessor :connection
4
    attr_accessor :http
5
    attr_accessor :token
6
7
    attr_reader :me
8
9
    def initialize(opts = {})
10
      @endpoint = 'https://api.medium.com/v1/'
11
      if opts.key? :integration_token
12
        @connection = MediumSdk::Connection::IntegrationToken.new opts
13
      elsif opts.key? :client_id
14
        @connection = MediumSdk::Connection::AuthCode.new opts
15
      end
16
    end
17
18
    def get_url(url)
19
      return @connection.http.get do |req|
20
        req.url url
21
      end
22
    end
23
24
    def body_key(res, key)
25
      return res.body.key?(key) ? res.body[key] : nil
26
    end
27
28
    def me()
29
      @me = body_key get_url('me'), 'data'
30
      return @me
31
    end
32
33
    def user_publications(user_id)
34
      res = get_url File.join 'users', user_id, 'publications'
35
      return body_key(res, 'data')
36
    end
37
38
    def post(post)
39
      url = ''
40
      if post.key? :publicationId
41
        publication_id = post[:publicationId].clone
42
        post.delete :publicationId
43
        url = File.join 'publications', publication_id, 'posts'
44
      else
45
        me unless @me
46
        unless @me.is_a?(Hash) && @me.key?('id') && @me['id'].to_s.length>0
47
          raise 'Authorized User Id is unknown'
48
        end
49
        id = @me['id']
50
        url = File.join 'users', id, 'posts'
51
      end
52
      res = @connection.http.post do |req|
53
        req.url url
54
        req.body = post
55
      end
56
      return body_key(res, 'data')
57
    end
58
59
    def publication_contributors(publication_id)
60
      res = get_url File.join 'publications', publication_id, 'contributors'
61
      return body_key(res, 'data')
62
    end
63
64
  end
65
end
66