kemal/src/kemal/param_parser.cr

68 lines
1.6 KiB
Crystal
Raw Normal View History

2015-11-06 18:24:38 +00:00
require "json"
# ParamParser parses the request contents including query_params and body
# and converts them into a params hash which you can within the environment
# context.
2015-11-06 18:24:38 +00:00
alias AllParamTypes = Nil | String | Int64 | Float64 | Bool | Hash(String, JSON::Type) | Array(JSON::Type)
2015-10-28 18:38:24 +00:00
class Kemal::ParamParser
URL_ENCODED_FORM = "application/x-www-form-urlencoded"
2015-11-06 18:24:38 +00:00
APPLICATION_JSON = "application/json"
2015-10-28 18:30:27 +00:00
def initialize(@route, @request)
2015-11-06 18:24:38 +00:00
@params = {} of String => AllParamTypes
2015-10-28 18:30:27 +00:00
end
def parse
parse_request
end
def parse_request
2016-01-12 19:37:12 +00:00
parse_url_params
parse_query
parse_body
2015-11-06 18:24:38 +00:00
parse_json
2015-10-28 18:30:27 +00:00
@params
end
def parse_body
return if (@request.headers["Content-Type"]? =~ /#{URL_ENCODED_FORM}/).nil?
parse_part(@request.body)
end
def parse_query
parse_part(@request.query)
end
2016-01-12 19:37:12 +00:00
def parse_url_params
parse_part(@request.url_params.to_s)
end
2015-12-31 12:03:11 +00:00
# Parses JSON request body if Content-Type is `application/json`.
# If request body is a JSON Hash then all the params are parsed and added into `params`.
# If request body is a JSON Array it's added into `params` as `_json` and can be accessed
# like params["_json"]
2015-11-06 18:24:38 +00:00
def parse_json
return unless @request.body && @request.headers["Content-Type"]? == APPLICATION_JSON
2015-11-10 11:30:16 +00:00
2015-11-06 18:24:38 +00:00
body = @request.body as String
case json = JSON.parse(body).raw
2015-11-10 11:30:16 +00:00
when Hash
json.each do |k, v|
@params[k as String] = v as AllParamTypes
end
when Array
@params["_json"] = json
2015-11-06 18:24:38 +00:00
end
end
def parse_part(part)
return unless part
HTTP::Params.parse(part) do |key, value|
@params[key] ||= value
end
end
2015-10-28 18:30:27 +00:00
end