我有一个简单的POST Grape端点,后台有Wisper pub / sub:
module Something
class Doit < Grape::API
post :now do
service = SomePub.new
service.subscribe(SomeSub.new)
service.call(params)
end
end
end
以下是实际计算发生的SomeSub
:
class SomeSub
def do_calculations(payload)
{result: "42"}.to_json
end
end
SomePub
也很简单:
class SomePub
include Wisper::Publisher
def call(payload)
broadcast(:do_calculations, payload)
end
end
所以我需要在调用Grape的{result: "42"}
端点时使用JSON post :now
进行响应。
不幸的是,这种方式不起作用,而我所拥有的是:
{"local_registrations":[{"listener":{},"on":{},"with":null,"prefix":"","allowed_classes":[],"broadcaster":{}}]}
来自Wisper的wiki的例子并没有多大帮助(https://github.com/krisleech/wisper/wiki/Grape)
任何想法如何实际传递SomePub#do_calculations
结果,这是Grape的端点调用的结果?
答案 0 :(得分:3)
PubSub模式的重点是发布者完全不知道其订阅者。您要实现的目标是将订阅者的结果传递回Publisher,这违背了所有想法。
但是,您可以做的是使您的订阅者也成为发布者并在单独的订阅者中收集回复。
请注意,这是示例代码,因为我手边没有安装Grape(但是,希望它有效):
class ResponseListener
attr_reader :response
def initialize
@response = {}
end
def collect_response(item)
@response.merge!(item) # customize as you wish
end
end
class SomeSub
include Wisper::Publisher
def do_calculations(payload)
broadcast(:collect_response, result: "42")
end
end
module Something
class Doit < Grape::API
post :now do
response_listener = ResponseListener.new
# globally subscribe response_listener to all events it can respond to
Wisper.subscribe(response_listener)
service = SomePub.new
service.subscribe(SomeSub.new)
service.call(params)
response_listener.response.to_json # render collected response
end
end
end