client.rb 1.45 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
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]
    end

    def connection
      Faraday.new(connection_options) do |req|
        req.adapter :net_http
      end
    end

    def self.resources
      {
          items: ItemResource,
          collections: CollectionResource,
          communities: CommunityResource,
          status: StatusResource,
          authentication: AuthenticationResource
      }
    end

    def method_missing(name, *args, &block)
29
      resource(name) || super
30
31
32
33
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
65
66
67
68
    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,
          headers: {
              content_type: 'application/json',
              'rest-dspace-token' => access_token.to_s
          }
      }
    end
  end
end