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

5
    attr_accessor :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
        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
          items: ::Dspace::Resources::ItemResource,
          collections: ::Dspace::Resources::CollectionResource,
          communities: ::Dspace::Resources::CommunityResource,
          status: ::Dspace::Resources::StatusResource,
30
          authentication: ::Dspace::Resources::AuthenticationResource,
31
          schema_registry: ::Dspace::Resources::SchemaRegistryResource,
32
33
          hierarchy: ::Dspace::Resources::HierarchyResource,
          query_report: ::Dspace::Resources::QueryReportResource
34
35
36
37
      }
    end

    def method_missing(name, *args, &block)
38
      resource(name) || super
39
40
41
42
43
44
45
46
47
48
    end

    def resources
      @resources ||= {}
    end

    def is_running?
      resource(:status).test
    end

49
50
51
52
    def status
      resource(:status).status
    end

53
    def login(email, password)
Bruno Nocera Zanette's avatar
Bruno Nocera Zanette committed
54
      @access_token = resource(:authentication).login(email: email, password: password)
55
56
57
    end

    def logout
58
59
      (response = resource(:authentication).logout) && @access_token = nil
      response
60
61
62
63
64
65
    end

    private

    def resource(name)
      if self.class.resources.keys.include?(name)
66
        resources[name] = self.class.resources[name].new(connection: connection)
67
68
69
70
71
      end
    end

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