~singpolyma/sgx-jmp

ref: 540996de59cef98525e2067da6951eb17f648a94 sgx-jmp/lib/roda_async.rb -rw-r--r-- 1.0 KiB
540996deStephen Paul Weber WIP 1 year, 1 month ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# frozen_string_literal: true

require "eventmachine"
require "promise"

module RodaAsync
	def self.configure(*, &block)
		@error_handler = block || ->(e) { EM.next_tick { raise e } }
	end

	def self.error_handler
		@error_handler
	end

	class DeferrableBody
		include EventMachine::Deferrable

		def to_proc
			@body_callback
		end

		def each(&block)
			@body_callback = block
		end
	end

	module RequestMethods
		def streaming_body
			body = DeferrableBody.new
			yield body.to_proc
			body
		end

		def block_result(result)
			case result
			when DeferrableBody
				super("")
				status, headers, = response.finish
				@env["async.callback"][[status, headers, result]]
				throw :async
			when Promise
				result.then { |r|
					super(r)
					@env["async.callback"][response.finish]
				}.catch(&RodaAsync.error_handler)
				throw :async
			when EM::Deferrable
				result.callback do |r|
					super(r)
					@env["async.callback"][response.finish]
				end
				result.errback(&RodaAsync.error_handler)
				throw :async
			else
				super(result)
			end
		end
	end
end