Class: Cocainum::Api

Inherits:
Object
  • Object
show all
Extended by:
Cocaine::Http
Defined in:
lib/cocainum/api.rb

Instance Method Summary collapse

Constructor Details

#initializeApi

Returns a new instance of Api.



20
21
22
# File 'lib/cocainum/api.rb', line 20

def initialize
  @handlers = {}
end

Instance Method Details

#execute(request, response) ⇒ Object



53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
# File 'lib/cocainum/api.rb', line 53

def execute(request, response)
  df = request.read
  df.callback do |rq|

    EM.synchrony do
      begin
        url = rq.url.to_s
        url_items = url.split('/')
        url_items.shift if url_items[0].empty?

        api_req = ApiRequest.new
        api_req.method = rq.method

        # version detection ###########################
        url_items[0].match(/^v[0-9.]+/) { |m|
          api_req.version = m[0]
          url_items.shift
        }

        # format detection ############################
        format = url.match(/\.([a-z]+)$/)
        if format && %w(json xml).include?(format[1])
          api_req.accept = format[1].to_sym
        elsif rq.headers.include?('Accept')
          header_accept = Hash[rq.headers['Accept'].split(',').map { |row|
            params = row.split(';')
            ver = ''
            row.match(/format=(v[0-9.]+)/) { |m| ver = m[1]}

            [params[0], {:version => ver}]
          }]
          if header_accept.key?('application/json')
            api_req.accept = :json
            api_req.version = header_accept['application/json'][:version]
          elsif header_accept.key?('application/xml')
            api_req.accept = :xml
            api_req.version = header_accept['application/xml'][:version]
          end
        end

        # content-type ################################
        api_req.content_type = rq.headers.key?('Content-Type') ? rq.headers['Content-Type'] : 'text/plain'

        # body parse ##################################
        api_req.request = case api_req.content_type
                          when 'application/json'
                            JSON.parse(rq.body, {symbolize_names:true})
                          when 'application/xml'
                            #(Nokogiri::XML(rq.body) do |config|
                            #  config.options = Nokogiri::XML::ParseOptions.STRICT | Nokogiri::XML::ParseOptions.NONET
                            #end).to_hash

                            Nokogiri::XML(rq.body).to_hash
                          else
                            {}
                        end
        api_req.action = url_items[0]

        api_resp = if @handlers[api_req.method] && @handlers[api_req.method][api_req.action]
          @handlers[api_req.method][api_req.action].call(api_req)
        else
          {:code => 400, :response => {:error_details => 'method unknown ' + api_req.method + ': ' + api_req.action + ' (' + @handlers.inspect + ')'}}
        end


        case api_req.accept
          when :json
            api_resp[:response] = prepare_hash_for_json(api_resp[:response])
            msg = JSON.generate(api_resp[:response])
            content_type = 'application/json'
          when :xml
            msg = api_resp[:response].to_xml
            content_type = 'application/xml'
          else
            content_type = 'plain/html'
            msg = 'error'
        end
=begin
        msg = 'Message: ' + (rq.query.key?('message') ? rq.query['message'][0] : '') + '<br/>Body: ' + rq.body + '<br/>Headers: ' + rq.headers.inspect + '<br/>Test: '

        service = Cocaine::Synchrony::Service.new 'DummyService'
        ch  = service.enqueue('write_dummy', 'sent this message123')
        msg1 = ch.collect(1)
        msg += '<br/>URL: ' + url
        msg += '<br/>Method: ' + api_req.method
        msg += '<br/>Version: ' + api_req.version
        msg += '<br/>Accept: ' + api_req.accept.to_s
        msg += '<br/>Content-type: ' + api_req.content_type
        msg += '<br/>Query: ' + api_req.request.inspect
        msg += '<br/>' + msg1.inspect
=end

        headers     = [['Content-Type', content_type + '; charset=UTF-8'],
                       ['Content-Length', msg.size.to_s],
                       ['Expires', 'Thu, 19 Nov 1981 08:52:00 GMT'],
                       ['Cache-Control', 'no-store, no-cache, must-revalidate, post-check=0, pre-check=0']
        ]
        api_resp[:headers].each {|k, v|
          headers << [k, v]
        }
      rescue Exception=> e
        msg = 'Message: ' + e.message + '<br/>'
        msg += 'Stacktrace:<br/>' + e.backtrace.join('<br/>')
      end

      response.write_headers(api_resp[:code], headers)
      response.body = msg
      response.close
    end
  end
end

#on(method, event, handler) ⇒ Object



24
25
26
27
# File 'lib/cocainum/api.rb', line 24

def on(method, event, handler)
  @handlers[method] = {} unless @handlers.key?(method)
  @handlers[method][event] = handler
end

#prepare_array_for_json(a) ⇒ Object



29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/cocainum/api.rb', line 29

def prepare_array_for_json(a)
  a.shift
  a.map do |item|
    if Array === item
      prepare_array_for_json(item)
    elsif Hash === item
      prepare_hash_for_json(item)
    else
      item
    end
  end
end

#prepare_hash_for_json(a) ⇒ Object



42
43
44
45
46
47
48
49
50
51
# File 'lib/cocainum/api.rb', line 42

def prepare_hash_for_json(a)
  Hash[a.map do |k, v|
    if Array === v
      v = prepare_array_for_json(v)
    elsif Hash === v
      v = prepare_hash_for_json(v)
    end
    [k, v]
  end]
end