Class: MediumApi::Client

Inherits:
Object
  • Object
show all
Includes:
HTTParty
Defined in:
lib/medium_api/client.rb

Constant Summary collapse

CODE_TO_ERROR =
{
    400 => Error::BadRequestError,
    401 => Error::UnauthorizedError,
    403 => Error::ForbiddenError
}

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(api_key:) ⇒ Client

Returns a new instance of Client.



15
16
17
18
19
# File 'lib/medium_api/client.rb', line 15

def initialize(api_key:)
    @api_key = api_key

    self.class.headers("Authorization" => "Bearer #{api_key}")
end

Instance Attribute Details

#api_keyObject (readonly)

Returns the value of attribute api_key.



13
14
15
# File 'lib/medium_api/client.rb', line 13

def api_key
  @api_key
end

Instance Method Details

#create_user_post(user_id, post_attributes) ⇒ Object



39
40
41
42
43
# File 'lib/medium_api/client.rb', line 39

def create_user_post(user_id, post_attributes)
    with_error_handling do
        self.class.post("/users/#{user_id}/posts", body: Utils.camelcase_keys(post_attributes))
    end
end

#meObject



21
22
23
24
25
# File 'lib/medium_api/client.rb', line 21

def me
    with_error_handling do
        self.class.get('/me')
    end
end

#publication_contributors(publication_id) ⇒ Object



33
34
35
36
37
# File 'lib/medium_api/client.rb', line 33

def publication_contributors(publication_id)
    with_error_handling do
        self.class.get("/publications/#{publication_id}/contributors")
    end
end

#user_publications(user_id) ⇒ Object



27
28
29
30
31
# File 'lib/medium_api/client.rb', line 27

def user_publications(user_id)
    with_error_handling do
        self.class.get("/users/#{user_id}/publications")
    end
end

#with_error_handlingObject

Raises:

  • (error_class)


45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/medium_api/client.rb', line 45

def with_error_handling
    response = yield

    return response['data'] if response.success?

    message = response['errors'].first['message']
    error_class = CODE_TO_ERROR[response.code] || MediumApi::Error

    raise error_class, message
    # raise Error::UnauthorizedError, message if response.code == 401
    # raise Error::BadRequestError, message if response.code == 400
    # raise Error::ForbiddenError, message if response.code == 403
    # raise Error
end