Class: Racknga::Middleware::JSONP — racknga - ラングバ

Class: Racknga::Middleware::JSONP

Inherits:
Object
  • Object
show all
Defined in:
lib/racknga/middleware/jsonp.rb

Overview

This is a middleware that provides JSONP support.

If you use this middleware, your Rack application just returns JSON response.

Usage:

require "racknga"

use Rack::ContentLength
use Racknga::Middleware::JSONP
json_application = Proc.new do |env|
  [200,
   {"Content-Type" => "application/json"},
   ['{"Hello": "World"}']]
end
run json_application

Results:

% curl 'http://localhost:9292/'
{"Hello": "World"}
% curl 'http://localhost:9292/?callback=function'
function({"Hello": "World"})

You can use this middleware with Racknga::Middleware::Cache. You should use this middleware before the cache middleware:

use Racknga::Middleawre::JSONP
use Racknga::Middleawre::Cache, :database_path => "var/cache/db"
run YourApplication

If you use this middleware after the cache middleware, the cache middleware will cache many responses that just only differ callback parameter value. Here are examples:

Recommended case:

use Racknga::Middleawre::JSONP
use Racknga::Middleawre::Cache, :database_path => "var/cache/db"
run YourApplication

Requests:

http://localhost:9292/                    -> no cache. cached.
http://localhost:9292/?callback=function1 -> use cache.
http://localhost:9292/?callback=function2 -> use cache.
http://localhost:9292/?callback=function3 -> use cache.
http://localhost:9292/?callback=function1 -> use cache.

Not recommended case:

use Racknga::Middleawre::Cache, :database_path => "var/cache/db"
use Racknga::Middleawre::JSONP
run YourApplication

Requests:

http://localhost:9292/                    -> no cache. cached.
http://localhost:9292/?callback=function1 -> no cache. cached.
http://localhost:9292/?callback=function2 -> no cache. cached.
http://localhost:9292/?callback=function3 -> no cache. cached.
http://localhost:9292/?callback=function1 -> use cache.

Defined Under Namespace

Classes: Writer

Instance Method Summary (collapse)

Constructor Details

- (JSONP) initialize(application)

A new instance of JSONP



80
81
82
# File 'lib/racknga/middleware/jsonp.rb', line 80

def initialize(application)
  @application = application
end

Instance Method Details

- (Object) call(environment)

For Rack.



85
86
87
88
89
90
91
92
93
94
95
96
# File 'lib/racknga/middleware/jsonp.rb', line 85

def call(environment)
  request = Rack::Request.new(environment)
  callback = request["callback"]
  update_cache_key(request) if callback
  status, headers, body = @application.call(environment)
  return [status, headers, body] unless callback
  header_hash = Rack::Utils::HeaderHash.new(headers)
  return [status, headers, body] unless json_response?(header_hash)
  body = Writer.new(callback, body)
  update_content_type(header_hash)
  [status, header_hash, body]
end