[英]Grape API - problem making a post request using curl with data option
[英]Wisper and Grape return results from a POST request
我有一個簡單的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的post :now
endpoint時用JSON {result: "42"}
進行響應。
不幸的是,這種方式不起作用,我所擁有的是:
{"local_registrations":[{"listener":{},"on":{},"with":null,"prefix":"","allowed_classes":[],"broadcaster":{}}]}
來自Wisper維基的那個例子並沒有多大幫助( https://github.com/krisleech/wisper/wiki/Grape )
任何想法如何實際傳遞SomePub#do_calculations
結果,作為Grape的端點調用的結果?
PubSub模式的重點是Publisher 完全沒有意識到它的訂閱者。 您要實現的目標是將Subscriber的結果傳遞回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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.