Class: Ki::Middleware::ApiHandler

Inherits:
Object
  • Object
show all
Includes:
BaseMiddleware
Defined in:
lib/ki/middleware/api_handler.rb

Overview

Handles all API calls

Any json request is considered an api call. A request is considered as json if the format is .json or Content-Type header is set to ‘application/json’

If the query param ‘redirect_to’ is given, the response will not contain the json output from the url, instead it will redirect to the url given

Instance Method Summary collapse

Methods included from BaseMiddleware

#initialize

Instance Method Details

#call(env) ⇒ Object



13
14
15
16
17
18
19
20
# File 'lib/ki/middleware/api_handler.rb', line 13

def call(env)
  req = BaseRequest.new env
  if req.json?
    resourcerize(req)
  else
    @app.call env
  end
end

#redirect_to(s) ⇒ Object



39
40
41
42
43
# File 'lib/ki/middleware/api_handler.rb', line 39

def redirect_to(s)
  resp = Rack::Response.new
  resp.redirect(s)
  resp.finish
end

#render(r) ⇒ Object



45
46
47
48
49
# File 'lib/ki/middleware/api_handler.rb', line 45

def render(r)
  resp = Rack::Response.new(r.result.to_json, r.status)
  resp['Content-Type'] = 'application/json'
  resp.finish
end

#resourcerize(req) ⇒ Object



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/ki/middleware/api_handler.rb', line 22

def resourcerize(req)
  klass = req.to_ki_model_class

  unless Model.descendants.include?(klass)
    fail InvalidUrlError.new("invalid url '#{req.path}'", 404)
  end

  model = klass.new(req.to_action, req.params)
  if req.params['redirect_to'].nil? # TODO: document this
    render model
  else
    redirect_to req.params['redirect_to'] # TODO: check for injection
  end
rescue ApiError => e
  render e
end