Skip to content

Commit

Permalink
Support uploading image for Post creation
Browse files Browse the repository at this point in the history
  • Loading branch information
akdarrah committed Feb 23, 2021
1 parent 237b7e8 commit 3b4ee06
Show file tree
Hide file tree
Showing 4 changed files with 40 additions and 3 deletions.
5 changes: 3 additions & 2 deletions lib/onepost/client.rb
Expand Up @@ -10,6 +10,7 @@ class Client

RAPID_API_HOST = "onepost1.p.rapidapi.com"
TIMEOUT = 180
JSON_CONTENT_TYPE = "application/json"

attr_accessor :rapid_api_key, :secret_key

Expand All @@ -32,9 +33,9 @@ def default_body

def default_headers
{
"Content-Type" => "application/json",
"Content-Type" => JSON_CONTENT_TYPE,
"x-rapidapi-key" => rapid_api_key,
"x-rapidapi-host" => Onepost::Client::RAPID_API_HOST
"x-rapidapi-host" => RAPID_API_HOST
}
end

Expand Down
6 changes: 5 additions & 1 deletion lib/onepost/post.rb
Expand Up @@ -41,9 +41,13 @@ def create_post(options={})
body = default_body.merge(options.fetch(:body, {}))
headers = default_headers.merge(options.fetch(:headers, {}))

if headers["Content-Type"] == Onepost::Client::JSON_CONTENT_TYPE
body = body.to_json
end

response = HTTParty.post(url, {
query: query,
body: body.to_json,
body: body,
headers: headers,
timeout: Onepost::Client::TIMEOUT
})
Expand Down
Binary file added test/files/redrocks.jpg
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
32 changes: 32 additions & 0 deletions test/onepost_post_test.rb
Expand Up @@ -71,6 +71,38 @@ def test_can_create_a_new_post
assert_equal 1, data["id"]
end

def test_can_create_a_new_post_with_image_upload
skip "WebMock does not support matching body for multipart/form-data requests yet :("

stub_request(:post, "https://onepost1.p.rapidapi.com/api/v1/posts?secret_key=67890")
.with(
body: "post%5Bbody%5D=Red%20Rocks%21&post%5Bauthorized_page_ids%5D%5B%5D=10&post%5Bauthorized_page_ids%5D%5B%5D=11&post%5Bimage%5D=%2FUsers%2Fadam%2FDeveloper%2Fonepost%2Fonepost-gem%2Ftest%2Ffiles%2Fredrocks.jpg",
headers: {
'Accept'=>'*/*',
'Accept-Encoding'=>'gzip;q=1.0,deflate;q=0.6,identity;q=0.3',
'Content-Type'=>'multipart/form-data',
'User-Agent'=>'Ruby',
'X-Rapidapi-Host'=>'onepost1.p.rapidapi.com',
'X-Rapidapi-Key'=>'12345'
}
)
.to_return(status: 200, body: example_post_data.to_json, headers: {})

data = @client.create_post(
headers: {
"Content-Type" => "multipart/form-data"
},
body: {
post: {
body: "Red Rocks!",
authorized_page_ids: [10, 11],
image: File.join(Dir.pwd, "test/files/redrocks.jpg")
}
}
)
assert_equal 1, data["id"]
end

def test_can_update_a_post
stub_request(:put, "https://onepost1.p.rapidapi.com/api/v1/posts/5?secret_key=67890")
.with(
Expand Down

0 comments on commit 3b4ee06

Please sign in to comment.