can upload file to datagouv
This commit is contained in:
parent
f7226ac625
commit
77a9a2ba12
2 changed files with 75 additions and 0 deletions
47
app/lib/api_datagouv/api.rb
Normal file
47
app/lib/api_datagouv/api.rb
Normal file
|
@ -0,0 +1,47 @@
|
|||
class APIDatagouv::API
|
||||
class RequestFailed < StandardError
|
||||
def initialize(url, response)
|
||||
msg = <<-TEXT
|
||||
HTTP error code: #{response.code}
|
||||
#{response.body}
|
||||
TEXT
|
||||
|
||||
super(msg)
|
||||
end
|
||||
end
|
||||
|
||||
class << self
|
||||
def upload(path)
|
||||
io = File.new(path, 'r')
|
||||
response = Typhoeus.post(
|
||||
datagouv_upload_url,
|
||||
body: {
|
||||
file: io
|
||||
},
|
||||
headers: { "X-Api-Key" => datagouv_secret[:api_key] }
|
||||
)
|
||||
io.close
|
||||
|
||||
if response.success?
|
||||
response.body
|
||||
else
|
||||
raise RequestFailed.new(datagouv_upload_url, response)
|
||||
end
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def datagouv_upload_url
|
||||
[
|
||||
datagouv_secret[:api_url],
|
||||
"/datasets/", datagouv_secret[:ds_demarches_publiques_dataset],
|
||||
"/resources/", datagouv_secret[:ds_demarches_publiques_resource],
|
||||
"/upload/"
|
||||
].join
|
||||
end
|
||||
|
||||
def datagouv_secret
|
||||
Rails.application.secrets.datagouv
|
||||
end
|
||||
end
|
||||
end
|
28
spec/lib/api_datagouv/api_spec.rb
Normal file
28
spec/lib/api_datagouv/api_spec.rb
Normal file
|
@ -0,0 +1,28 @@
|
|||
describe APIDatagouv::API do
|
||||
describe '#upload' do
|
||||
let(:subject) { APIDatagouv::API.upload(Tempfile.new.path) }
|
||||
|
||||
before do
|
||||
stub_request(:post, /https:\/\/www.data.gouv.fr\/api/)
|
||||
.to_return(body: body, status: status)
|
||||
end
|
||||
|
||||
context "when response ok" do
|
||||
let(:status) { 200 }
|
||||
let(:body) { "ok" }
|
||||
|
||||
it 'returns body response' do
|
||||
expect(subject).to eq body
|
||||
end
|
||||
end
|
||||
|
||||
context "when responds with error" do
|
||||
let(:status) { 400 }
|
||||
let(:body) { "oops ! There is a problem..." }
|
||||
|
||||
it 'raise error' do
|
||||
expect { subject }.to raise_error(APIDatagouv::API::RequestFailed)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
Loading…
Add table
Reference in a new issue