Class: Ki::Middleware::ApiHandler

Inherits:
Object
  • Object
show all
Includes:
Helpers::RedirectTo, 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



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

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

#render(model) ⇒ Object



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

def render(model)
  if model.is_a?(ApiError) || model.params['redirect_to'].nil?
    resp = Rack::Response.new(model.result.to_json, model.status)
    resp['Content-Type'] = 'application/json'
    resp.finish
  else
    redirect_to model.params['redirect_to']
  end
end

#resourcerize(req) ⇒ Object



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

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)
  render model
rescue ApiError => e
  render e
end