bodyFieldIsRequired<B extends Body> function

Middleware bodyFieldIsRequired<B extends Body>(
  1. String fieldName
)

bodyFieldIsRequired check if the fieldName is present in the body if check failed return BadRequest response

Implementation

Middleware bodyFieldIsRequired<B extends Body>(String fieldName) {
  return (handler) {
    return (request) {
      Response? checkItem(Map<String, dynamic> item) {
        if (item[fieldName] == null) {
          final bodyResponse = BadRequest(
            'about:blank',
            'Required field is missing',
            'The required field \'$fieldName\' is missing',
            400,
            request.requestedUri.path,
            field: fieldName,
          );
          return generateResponse(request, bodyResponse);
        }
        return null;
      }

      final body = request.get<B>();
      final response = _checkData(body.data, checkItem);
      if (response != null) {
        return response;
      }
      return handler(request);
    };
  };
}