Sha256: 65f2d74e297d4b5b22af8a5f1c3d744a4c2517723f370bda2fbc1d75ee844fbc

Contents?: true

Size: 1.27 KB

Versions: 10

Compression:

Stored size: 1.27 KB

Contents

#!/usr/bin/ruby --

require "json/lexer"
require "cgi"

module JSONBroker

# CGI向けAPI
# パラメータ「request」の値をリクエストとして使う。
class Cgi
  def self.invoke( service )
    print "Content-type: application/json\n\n"
    cgi =  CGI.new
    request = cgi.params["request"].to_s

    print Broker.new( service ).invoke( request )
  end
end

# JSONリクエストを元にサービスのAPIを実行して結果をJSONで返す。
#
# リクエスト:
# {"method":<サービスメソッド名>, "params":[<引数1>, <引数2>]}
#
# レスポンス(正常時):
# [{"error":null, "result":<実行結果>}]
#
# レスポンス(エラー時):
# [{"error":<例外の詳細>, "result":null}]
#
class Broker
  def initialize ( service )
    @service = service
  end

  def invoke ( request )
    begin
      json = JSON::Lexer.new(request).nextvalue
      method   = json["method"]
      args       = json["params"]

      result = @service.send( method.to_sym, *args )
      return '[{"error":null, "result":' << result.to_json << "}]"
    rescue
      error =  $!.to_s + " : " + $!.backtrace.join("\n")
      return '[{"error":' << error.to_json << ', "result":null}]'
    end
  end
end

end

#print JSONBroker::Broker.new( "mii,aaa" ).invoke( '{"method":"to_s","params":[]}' )

Version data entries

10 entries across 10 versions & 1 rubygems

Version Path
unageanu-jiji-0.1.0 lib/jiji/util/json_broker.rb
unageanu-jiji-1.0.0 lib/jiji/util/json_broker.rb
unageanu-jiji-1.0.1 lib/jiji/util/json_broker.rb
unageanu-jiji-1.0.2 lib/jiji/util/json_broker.rb
unageanu-jiji-1.0.3 lib/jiji/util/json_broker.rb
unageanu-jiji-1.1.0 lib/jiji/util/json_broker.rb
unageanu-jiji-1.1.1 lib/jiji/util/json_broker.rb
unageanu-jiji-1.1.2 lib/jiji/util/json_broker.rb
unageanu-jiji-1.1.3 lib/jiji/util/json_broker.rb
unageanu-jiji-1.1.4 lib/jiji/util/json_broker.rb