Skip to content

Builders and Parsers

Juli Tera edited this page Apr 12, 2024 · 3 revisions

Builders and parsers are protocol specific classes that build a request using operation input and parse a response into an output object. Builders and parsers have a 1:1 mapping to Smithy complex shapes (Structure, List, Map, Operation).

Builders

Builders build a transport specific request object intended to be sent to the service using input shapes (serialization). Builders have access to a request object, to populate the headers, method, and body.

Assume the following Smithy model using a JSON protocol:

module SampleService
  # @api private
  module Builders

    class CreateHighScore
      def self.build(http_req, input:)
        http_req.http_method = 'POST'
        http_req.append_path('/high_scores')
        params = Hearth::Query::ParamList.new
        http_req.append_query_param_list(params)

        http_req.headers['Content-Type'] = 'application/json'
        data = {}
        data[:high_score] = Builders::HighScoreParams.build(input[:high_score]) unless input[:high_score].nil?
        http_req.body = StringIO.new(Hearth::JSON.dump(data))
      end
    end

  end 
end

Parsers

Parsers parse a transport specific response object from the service intended for the client (deserialization). Parsers have access to the response object to inspect the status code, headers, and body.

module SampleService
  # @api private
  module Parsers

    class CreateHighScore
      def self.parse(http_resp)
        data = Types::CreateHighScoreOutput.new
        data.location = http_resp.headers['Location']
        json = Hearth::JSON.parse(http_resp.body.read)
        data.high_score = Parsers::HighScoreAttributes.parse(json)
        data
      end
    end

  end
end