client.rb 1.87 KB
Newer Older
1
2
3
4
5
6
7
8
9
module Dspace
  class Client
    DSPACE_API = 'https://demo.dspace.org'

    attr_reader :access_token

    def initialize(options = {})
      @access_token = options.with_indifferent_access[:access_token]
      @dspace_api = options.with_indifferent_access[:dspace_api]
10
      @logger = options.with_indifferent_access[:logger]
11
12
13
14
    end

    def connection
      Faraday.new(connection_options) do |req|
15
16
        req.request :multipart
        req.request :url_encoded
17
        req.use(Faraday::Response::Logger, @logger) unless @logger.nil?
18
        req.adapter :net_http_persistent
19
20
21
22
23
      end
    end

    def self.resources
      {
24
25
26
27
28
          items: ::Dspace::Resources::ItemResource,
          collections: ::Dspace::Resources::CollectionResource,
          communities: ::Dspace::Resources::CommunityResource,
          status: ::Dspace::Resources::StatusResource,
          authentication: ::Dspace::Resources::AuthenticationResource
29
30
31
32
      }
    end

    def method_missing(name, *args, &block)
33
      resource(name) || super
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
    end

    def resources
      @resources ||= {}
    end

    def is_running?
      resource(:status).test
    end

    def login(email, password)
      @access_token = resource(:authentication).login(email, password)
    end

    def logout
      resource(:authentication).logout
      @access_token = nil
    end

    private

    def resource(name)
      if self.class.resources.keys.include?(name)
        resources[name] ||= self.class.resources[name].new(connection: connection)
        resources[name]
      end
    end

    def connection_options
      {
          url: @dspace_api || DSPACE_API,
65
66
67
          ssl: {
              verify: false
          },
68
69
          headers: {
              content_type: 'application/json',
70
71
              'rest-dspace-token' => access_token.to_s,
              user_agent: "dspace-rest-client #{Dspace::VERSION}"
72
73
74
75
76
          }
      }
    end
  end
end