Module: Cyclid::API::APIHelpers
- Defined in:
- app/cyclid/sinatra/api_helpers.rb
Overview
Sinatra helpers
Instance Method Summary collapse
-
#json_response(id, description) ⇒ Object
Return a RESTful JSON response.
-
#parse_request_body ⇒ Object
Safely parse & validate the request body.
-
#request_body ⇒ Object
Return the raw request body.
Instance Method Details
#json_response(id, description) ⇒ Object
Return a RESTful JSON response
67 68 69 |
# File 'app/cyclid/sinatra/api_helpers.rb', line 67 def json_response(id, description) Oj.dump('id' => id, 'description' => description) end |
#parse_request_body ⇒ Object
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. halt_with_json_response(400, Errors::HTTPErrors::INVALID_JSON, ex.) 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 |
#request_body ⇒ Object
Return the raw request body
26 27 28 29 |
# File 'app/cyclid/sinatra/api_helpers.rb', line 26 def request_body request.body.rewind request.body.read end |