官术网_书友最值得收藏!

How to do it...

  1. Open the service object we created in the previous recipe. We'll modify the service object to be able to call an external microservice responsible for managing attachments. For the sake of simplicity, we'll use an HTTP client that is provided in the Ruby standard library. The service object should be in the app/services/attachments_service.rb file:
class AttachmentsService

BASE_URI = "http://attachment-service.yourorg.example.com/"

def upload(message_id, user_id, file_name, data, media_type)
body = {
user_id: user_id,
file_name: file_name,
data: StringIO.new(Base64.decode64(params[:file]
[:data]), 'rb'),
message: message_id,
media_type: media_type
}.to_json
uri = URI("#{BASE_URI}attachment")
headers = { "Content-Type" => "application/json" }
Net::HTTP.post(uri, body, headers)
end

end
  1. Open the attachments_controller.rb file, located in pichat/app/controllers/, and look at the following create action. Because of the refactoring work done in the previous chapter, we require only a small change to make the controller work with our new service object:
class AttachmentsController < ApplicationController
# POST /messages/:message_id/attachments
def create
service = AttachmentService.new
response = service.upload(params[:message_id], current_user.id,
params[:file][:name], params[:file][:data],
params[:media_type])
json_response(response.body, response.code)
end
# ...
end
主站蜘蛛池模板: 马山县| 南康市| 内乡县| 池州市| 苏尼特右旗| 中牟县| 天气| 同德县| 玉田县| 贵阳市| 义乌市| 理塘县| 集贤县| 汉源县| 涿鹿县| 沁阳市| 阿克陶县| 开阳县| 曲水县| 丹阳市| 扶沟县| 沂源县| 赤水市| 大姚县| 石林| 阿拉善右旗| 蓬莱市| 淄博市| 瑞金市| 安达市| 阳新县| 乌兰浩特市| 成武县| 浦县| 博白县| 汨罗市| 河北省| 晋州市| 萨嘎县| 塔城市| 措美县|