# frozen_string_literal: true require "faraday" require "dry/monads" require "json_schema" module Datacite # The connection to DataCite API class Client include Dry::Monads[:result] # @param [String] username # @param [String] password # @param [String] host def initialize(username:, password:, host: "api.test.datacite.org") @conn = Faraday.new( url: "https://#{host}", headers: headers ) do |conn| conn.request :json conn.request :authorization, :basic, username, password conn.response :json end end # Creates a random DOI # @param [String] prefix # @returns [Dry::Monads::Result] def autogenerate_doi(prefix:) request_body = AutogenerateDoiRequestBody.new(prefix: prefix).to_json register(request_body) end # Creates a specific DOI # @param [String] prefix # @param [String] suffix # @returns [Dry::Monads::Result] def register_doi(prefix:, suffix:) request_body = RegisterDoiRequestBody.new(prefix: prefix, suffix: suffix).to_json register(request_body) end # Update a DOI # @param [String] id # @param [String] value # @returns [Dry::Monads::Result] def update(id:, attributes:) Validator.validate!(attributes) request_body = { data: { attributes: attributes } } response = conn.put("/dois/#{id}", request_body.to_json) response.success? ? Success(Response.new(response)) : Failure(response) end private # @returns [Dry::Monads::Result] def register(request_body) response = conn.post("/dois", request_body) response.success? ? Success(Response.new(response)) : Failure(response) end def headers { "Content-Type" => "application/vnd.api+json", "User-Agent" => "Datacite Ruby client version #{Datacite::VERSION}" } end attr_reader :conn end end