Class: Unrestful::EndpointsController

Inherits:
ApplicationController show all
Includes:
ActionController::Live
Defined in:
app/controllers/unrestful/endpoints_controller.rb

Constant Summary collapse

INVALID_PARAMS =
[:method, :service, :controller, :action, :endpoint]

Instance Method Summary collapse

Instance Method Details

#endpointObject



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
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
# File 'app/controllers/unrestful/endpoints_controller.rb', line 12

def endpoint
    method = params[:method]
    service = params[:service]
			service_class = service.camelize.singularize
			
			arguments = params.to_unsafe_h.symbolize_keys.reject { |x| INVALID_PARAMS.include? x }

			klass = "::Rpc::#{service_class}".constantize
    
    raise NameError, "#{klass} is not a Unrestful::RpcController" unless klass <= ::Unrestful::RpcController
			actor = klass.new
			
			live = actor.live_methods.include? method
			async = actor.async_methods.include? method

    actor.instance_variable_set(:@service, service)
			actor.instance_variable_set(:@method, method)
			actor.instance_variable_set(:@request, request)
			actor.instance_variable_set(:@response, response)
			actor.instance_variable_set(:@live, live)
			actor.instance_variable_set(:@async, async)

    # only public methods
    raise "#{klass} doesn't have a method called #{method}" unless actor.respond_to? method


			response.headers['X-Live'] = live ? 'true' : 'false'
			response.headers['X-Async'] = async ? 'true' : 'false'

			return if request.head?

			if async
				@job = AsyncJob.new
				response.headers['X-Async-JobID'] = @job.job_id
				@job.update(AsyncJob::ALLOCATED)
				actor.instance_variable_set(:@job, @job)
			end

			response.headers['Content-Type'] = 'text/event-stream' if live

			actor.before_callbacks
			if arguments.count == 0
				payload = actor.send(method)
			else
				payload = actor.send(method, arguments)
			end

			raise LiveError if live && !payload.nil?

			unless live 
				if payload.nil?
					render json: Unrestful::SuccessResponse.render({}.to_json)
				else
					render json: Unrestful::SuccessResponse.render(payload.as_json) 
				end
			end

    actor.after_callbacks
rescue NameError => exc
    not_found(exc: exc)
rescue ArgumentError => exc
    fail(exc: exc)
rescue ::Unrestful::FailError => exc
			fail(exc: exc)
		rescue ::Unrestful::Error => exc
			fail(exc: exc)
		rescue IOError
			# ignore as this could be the client disconnecting during streaming
		rescue => exc
			fail(exc: exc, status: :internal_server_error)
		ensure 
			response.stream.close if live
end