diff --git a/app/lib/api_datagouv/api.rb b/app/lib/api_datagouv/api.rb new file mode 100644 index 000000000..2347e1e04 --- /dev/null +++ b/app/lib/api_datagouv/api.rb @@ -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 diff --git a/spec/lib/api_datagouv/api_spec.rb b/spec/lib/api_datagouv/api_spec.rb new file mode 100644 index 000000000..327c5e34d --- /dev/null +++ b/spec/lib/api_datagouv/api_spec.rb @@ -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