validateDto method
Check the input of req with schema and give the object.
source wins over the source of the DTO.
Implementation
Future<Object> validateDto(
DoxRequest req,
DtoSchema<Object> schema, {
Source? source,
}) async {
Source from = source ?? schema.source;
if (from == Source.auto) {
String method = req.method;
from = method == 'GET' || method == 'HEAD' || method == 'DELETE'
? Source.query
: Source.body;
}
Object? input;
bool text = true;
if (from == Source.query) {
input = forms.query(req.uri);
} else {
RequestBody body = req.requestBody;
switch (body.kind) {
case BodyKind.json:
input = body.json;
text = false;
case BodyKind.none:
input = <String, dynamic>{};
text = false;
case BodyKind.invalidJson:
throw BadRequestException(message: 'The body is not valid JSON');
case BodyKind.urlEncoded:
input = forms.parse(_pairs(body.text ?? ''));
case BodyKind.multipart:
input = forms.parse(body.parts ?? const <MapEntry<String, Object>>[]);
case BodyKind.other:
throw UnsupportedMediaTypeException();
}
}
DtoState state = DtoState(
root: input,
resolver: Dox().messages,
params: req.pathParams,
locale: req.locale,
text: text,
);
ParseResult<Object> result = await schema.run(input, state);
if (!result.success) throw ValidationException(message: result.errors);
return result.value as Object;
}