Method: Cyclid::API::APIHelpers#parse_request_body

Defined in:
app/cyclid/sinatra/api_helpers.rb

#parse_request_bodyObject

Safely parse & validate the request body



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'app/cyclid/sinatra/api_helpers.rb', line 32

def parse_request_body
  # Parse the the request
  begin
    request.body.rewind

    if request.content_type == 'application/json' or \
       request.content_type == 'text/json'

      data = Oj.load request.body.read
    elsif request.content_type == 'application/x-yaml' or \
          request.content_type == 'text/x-yaml'

      data = YAML.load request.body.read
    else
      halt_with_json_response(415, \
                              Errors::HTTPErrors::INVALID_JSON, \
                              "unsupported content type #{request.content_type}")
    end
  rescue Oj::ParseError, YAML::Exception => ex
    Cyclid.logger.debug ex.message
    halt_with_json_response(400, Errors::HTTPErrors::INVALID_JSON, ex.message)
  end

  # Sanity check the request
  halt_with_json_response(400, \
                          Errors::HTTPErrors::INVALID_JSON, \
                          'request body can not be empty') if data.nil?
  halt_with_json_response(400, \
                          Errors::HTTPErrors::INVALID_JSON, \
                          'request body is invalid') unless data.is_a?(Hash)

  return data
end