Module: Jsonatra::ParamsHelpers

Defined in:
lib/jsonatra/helpers/params.rb

Constant Summary collapse

JSON_CONTENT_TYPE =
'application/json'.freeze

Instance Method Summary collapse

Instance Method Details

#paramsObject

merges JSON POST body data over query params if provided



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/jsonatra/helpers/params.rb', line 8

def params
  unless @_params_hash
    @_params_hash = super

    # if we see what looks like JSON data, but have no Content-Type header...
    #
    if request.content_type.nil? or request.content_type == ''
      check_for_content_type_mismatch
    else
      content_type_header = request.content_type.split ';'
      if content_type_header.include? JSON_CONTENT_TYPE
        begin
          json_params_hash = JSON.parse request.body.read
          @_params_hash.merge! json_params_hash unless json_params_hash.nil?
        rescue JSON::ParserError => e
          begin
            msg = e.message.match(/\d+: (.+)/).captures.first
          rescue NoMethodError => noe
            msg = e.message
          end
          response.error = {
            type: 'json_parse_error',
            message: "could not process JSON: #{msg}",
            code: 400
          }
          halt
        end

        request.body.rewind
      else
        check_for_content_type_mismatch
      end
    end

    if settings.respond_to? :arrayified_params and settings.arrayified_params
      settings.arrayified_params.each do |param_name|
        array_or_comma_sep_param param_name
      end
    end

  end
  @_params_hash.merge! @params
  @_params_hash
end