I have a route that processes a form. This form is backed by a model class that performs the data validation. The validation outcome is a haxe.ds.Option<DynamicAccess<String>>
: None
if the request is OK, otherwise Some
with the validation errors (i.e. field => error message).
If the validation succeeds, the route returns the model data and a 201 status code.
If the validation fails, the route returns the anonymous structure providing the validation errors and a 422 status code.
My current code works, but it does not feel the right way to do the job:
import haxe.Json;
import httpstatus.HttpStatusCode;
import tink.http.Response;
@:post
@:header("Content-Type", "application/json")
public function handleForm(body: {field1: String, field2: String}) {
final model = new FormModel();
model.field1 = body.field1.trim();
model.field2 = body.field2.trim();
return switch model.validate() {
case None: new OutgoingResponse(Created, Json.stringify(model));
case Some(errors): new OutgoingResponse(UnprocessableEntity, Json.stringify(errors));
};
}
I’ve tried alternatives, but every trial resulted in error or unsatisfying outcome:
1 - Replaced @:header("Content-Type", "application/json")
meta by @:produces("application/json")
: the response Content-Type
is text/html
instead of application/json
.
2 - Removed the @:header
meta, and replaced tink.http.OutgoingResponse
by tink.web.Response
to avoid the Json.stringify()
calls and let tink_web
do the serialization :
return switch model.validate() {
case None: new Response(Created, model);
case Some(errors): new Response(UnprocessableEntity, errors);
};
The response is OK… except that the code doesn’t compile. It produces a return type error on the Some(errors)
case: haxe.DynamicAccess<String> should be FormModel
.
The lack of documentation does not help in understanding what should be done:
https://haxetink.github.io/tink_web/#/basics/response
Does anyone has a sample code showing the best way to implement the response handling?