client.rb 1.98 KB
Newer Older
1
2
3
4
module Dspace
  class Client
    DSPACE_API = 'https://demo.dspace.org'

5
    attr_reader :access_token
6
7
8
9

    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
          bitstreams: ::Dspace::Resources::BitstreamResource,
25
26
27
28
          items: ::Dspace::Resources::ItemResource,
          collections: ::Dspace::Resources::CollectionResource,
          communities: ::Dspace::Resources::CommunityResource,
          status: ::Dspace::Resources::StatusResource,
29
          authentication: ::Dspace::Resources::AuthenticationResource
30
31
32
33
      }
    end

    def method_missing(name, *args, &block)
34
      resource(name) || super
35
36
37
38
39
40
41
42
43
44
45
    end

    def resources
      @resources ||= {}
    end

    def is_running?
      resource(:status).test
    end

    def login(email, password)
46
      @access_token = resource(:authentication).login(email, password)
47
48
49
    end

    def logout
50
51
      resource(:authentication).logout
      @access_token = nil
52
53
54
55
56
57
    end

    private

    def resource(name)
      if self.class.resources.keys.include?(name)
58
59
        resources[name] ||= self.class.resources[name].new(connection: connection)
        resources[name]
60
61
62
63
64
      end
    end

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