getBody<T extends Body> function

Middleware getBody<T extends Body>(
  1. T deserializer(
    1. dynamic
    ), {
  2. required String objectName,
})

getBody parse the body based on Content-Type automatically

currently supported content-type are:

  • application/json
  • application/xml
  • application/x-www-form-urlencoded
  • multipart/form-data

Implementation

Middleware getBody<T extends Body>(T Function(dynamic) deserializer,
    {required String objectName}) {
  return (handler) {
    return (request) async {
      try {
        if (!request.headers.containsKey(HttpHeaders.contentTypeHeader)) {
          final body = BadRequest(
            'about:blank',
            'No Content-Type',
            'getBody need a content-type to parse the body accordingly',
            400,
            request.requestedUri.path,
          );
          return generateResponse(request, body);
        }
        final requestContentType =
            ContentType.parse(request.headers[HttpHeaders.contentTypeHeader]!);

        for (final contentType in supportedContentType) {
          if (contentType.primary == requestContentType.primaryType) {
            for (final sub in contentType.subs) {
              if (sub.sub == requestContentType.subType) {
                final content = await sub.getContent(request, objectName);
                final body = deserializer(content);
                return handler(request.set<T>(() => body));
              }
            }
          }
        }

        final body = BadRequest(
          'about:blank',
          'Not allowed Content-Type',
          'getBody middleware does\'t support \'$requestContentType\', allowed content-type are: \'${_allowedContentType.join('\', \'')}\'',
          400,
          request.requestedUri.path,
        );
        return generateResponse(request, body);
      } catch (error, stackTrace) {
        _logger.warning(error);
        _logger.warning(stackTrace);
        return Response.internalServerError();
      }
    };
  };
}