Class: Hyperdrive::HATEOAS

Inherits:
Object
  • Object
show all
Extended by:
Values
Defined in:
lib/hyperdrive/hateoas.rb

Class Method Summary collapse

Methods included from Values

default_config, default_cors_options, default_headers, definable_request_methods, http_request_methods, request_methods, supported_request_methods

Class Method Details

.call(env) ⇒ Object



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/hyperdrive/hateoas.rb', line 7

def self.call(env)
  if hyperdrive.resources.empty? || env['PATH_INFO'] != '/'
    raise Hyperdrive::Errors::NotFound
  end

  endpoints = hyperdrive.resources.map do |_,resource|
    resource.to_hash
  end

  api = {
          _links: { self: { href: '/' } },
          name: hyperdrive.config[:name],
          description: hyperdrive.config[:description],
          vendor: hyperdrive.config[:vendor],
          resources: endpoints
        }

  media_types = %w(hal+json json).map do |media_type|
    "application/vnd.#{hyperdrive.config[:vendor]}+#{media_type}"
  end

  media_types += %w(application/hal+json application/json)
  content_type = env['hyperdrive.accept'].best_of(media_types)
  body = if content_type =~ /json$/
            MultiJson.dump(api)
          else
            raise Errors::NotAcceptable.new(env['HTTP_ACCEPT'])
          end

  status = 200
  headers = {}
  headers['Access-Control-Allow-Origin'] = '*'
  headers['Access-Control-Allow-Methods'] = 'GET, HEAD, OPTIONS'
  headers['Allow'] = 'GET, HEAD, OPTIONS'
  headers['Content-Type'] = content_type
  [status, headers, [body]]
end