Sha256: 7e6bc6c5e752df0f7b253c4c46b45a582bfb8602cc7d7c0da7bfab854591286d

Contents?: true

Size: 1.71 KB

Versions: 2

Compression:

Stored size: 1.71 KB

Contents

module MediumSdk
  class Client
    attr_accessor :connection

    def initialize(opts = {})
      if opts.key? :client_id
        @connection = MediumSdk::Connection::AuthCode.new opts
      elsif opts.key? :integration_token
        @connection = MediumSdk::Connection::IntegrationToken.new opts
      end
    end

    def get_url(url)
      return @connection.http.get do |req|
        req.url url
      end
    end

    def body_key(res, key)
      if res.status >= 400
        raise "HTTP Error #{res.status} " + res.pretty_inspect
      end
      return res.body.key?(key) ? res.body[key] : nil
    end

    def me(reload = nil)
      if @_me.nil? || reload
        @_me = body_key get_url('me'), 'data'
      end
      return @_me
    end

    def me_id
      me unless @_me
      unless @_me.is_a?(Hash) && @_me.key?('id') && @_me['id'].to_s.length>0
        raise 'Authorized User Id is unknown'
      end
      return @_me['id']
    end

    def user_publications(user_id = nil)
      user_id = me_id if user_id.nil?
      res = get_url File.join 'users', user_id.to_s, 'publications'
      return body_key(res, 'data')
    end

    def post(post)
      url = ''
      if post.key? :publicationId
        publication_id = post[:publicationId].clone
        post.delete :publicationId
        url = File.join 'publications', publication_id, 'posts'
      else
        url = File.join 'users', me_id(), 'posts'
      end
      res = @connection.http.post do |req|
        req.url url
        req.body = post
      end
      return body_key(res, 'data')
    end

    def publication_contributors(publication_id)
      res = get_url File.join 'publications', publication_id, 'contributors'
      return body_key(res, 'data')
    end

  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
medium_sdk-0.0.3 lib/medium_sdk/client.rb
medium_sdk-0.0.2 lib/medium_sdk/client.rb