Validate body input with validator

Try to validate the request body as a json document using validator:

  • Returns the validated string input if the result of the validation is ok.
  • Answers a json error and returns null if something went wrong.
  • If no validator is set, returns the body without validation.

Example:

class ValidatedHandler
    super Handler

    redef var validator = new MyObjectValidator

    redef fun post(req, res) do
        var body = validate_body(req, res)
        if body == null then return # Validation error
        # At this point popcorn returned a HTTP 400 code with the validation error
        # if the validation failed.

        # TODO do something with the input
        print body
    end
end

class MyObjectValidator
    super ObjectValidator

    init do
        add new StringField("name", min_size=1, max_size=255)
    end
end

Property definitions

popcorn :: pop_json $ Handler :: validate_body
	# Validate body input with `validator`
	#
	# Try to validate the request body as a json document using `validator`:
	# * Returns the validated string input if the result of the validation is ok.
	# * Answers a json error and returns `null` if something went wrong.
	# * If no `validator` is set, returns the body without validation.
	#
	# Example:
	#
	# ~~~nit
	# class ValidatedHandler
	#	super Handler
	#
	#	redef var validator = new MyObjectValidator
	#
	#	redef fun post(req, res) do
	#		var body = validate_body(req, res)
	#		if body == null then return # Validation error
	#		# At this point popcorn returned a HTTP 400 code with the validation error
	#		# if the validation failed.
	#
	#		# TODO do something with the input
	#		print body
	#	end
	# end
	#
	# class MyObjectValidator
	#	super ObjectValidator
	#
	#	init do
	#		add new StringField("name", min_size=1, max_size=255)
	#	end
	# end
	# ~~~
	fun validate_body(req: HttpRequest, res: HttpResponse): nullable String do
		var body = req.body

		var validator = self.validator
		if validator == null then return body

		if not validator.validate(body) then
			res.json(validator.validation, 400)
			return null
		end
		return body
	end
lib/popcorn/pop_json.nit:70,2--115,4