Skip to content

Instantly share code, notes, and snippets.

@noel9999
Last active June 6, 2018 10:34
Show Gist options
  • Save noel9999/33b0a28b6139ea68a741fa226e6f6765 to your computer and use it in GitHub Desktop.
Save noel9999/33b0a28b6139ea68a741fa226e6f6765 to your computer and use it in GitHub Desktop.
一個 controller 的 action 需要去戳外部 api 三次的邏輯需求
class Webhook::CustomersController
# 下列的 action 會有三個步驟,每個步驟都會戳一次 api 然後檢查結果,如果失敗就要 render 結果並退出,成功的話就把資料繼續丟下去給後面的邏輯做
# 這樣的寫法很直覺的流水帳寫下去,但容易把邏輯弄得很肥大,也許之後會難以閱讀
# 然後思考一下發現裡面其實有某種邏輯的循環,但因為下一輪的循環依賴於前者,無法事先知道,所以嘗試使用 fiber 來處理
# 可參考版本:https://gist.github.com/noel9999/172946f174e144c2d48e33535fc5d376
def create
token = get_access_token(params[:merchant_id])
client = OpenApiClient.set(access_token: token).customers
customer = client.get("/#{params[:resource][:_id]}").json_body
mobile_phone, confirmed_at = customer.symbolize_keys.values_at(:mobile_phone, :confirmed_at)
(head :no_content and return) unless [mobile_phone, confirmed_at].all?(&:present?)
res = query_studioa_vip(mobile_phone)
(render json: res.json_body, status: :bad_request and return) if res['RESULT']['STATUS'].to_s != 'S'
result = if res.json_body['RESULT']['COUNT'].to_i > 0
UpdateCustomerService.new(token: token, raw_customer: res.json_body['DATA'], customer: customer).execute
else
CreateCustomerService.new(customer: customer).execute
end
if result.success?
render json: result.as_json, status: :ok
else
render json: result.as_json, status: :bad_request
end
end
protected
def query_studioa_vip(mobile_phone)
uri = URI(Settings.api_endpoint.query_vip)
json_parameters = {
"SYSPARAM": {
"DB_ID": "EPB",
"CHAR_SET": "eng",
"INCLUDE_NULL": "N"
},
"PARAMETER": {
"VIP_PHONE": mobile_phone
}
}
req = Net::HTTP::Post.new(uri, 'Content-Type' => 'application/json')
req.body = json_parameters.to_json
Net::HTTP.start(uri.hostname, uri.port) do |http|
http.request(req)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment