client.rb 2.01 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
        req.response :logger
16
17
        req.request :multipart
        req.request :url_encoded
18
        req.use(Faraday::Response::Logger, @logger) unless @logger.nil?
19
        req.adapter :net_http_persistent
20
21
22
23
24
      end
    end

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

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

    def resources
      @resources ||= {}
    end

    def is_running?
      resource(:status).test
    end

46
47
48
49
    def status
      resource(:status).status
    end

50
    def login(email, password)
Bruno Nocera Zanette's avatar
Bruno Nocera Zanette committed
51
      @access_token = resource(:authentication).login(email: email, password: password)
52
53
54
55
56
57
58
59
60
61
62
    end

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

    private

    def resource(name)
      if self.class.resources.keys.include?(name)
63
        resources[name] = self.class.resources[name].new(connection: connection)
64
65
66
67
68
      end
    end

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