jsonBody function

Middleware jsonBody()

JSON body parser middleware

Implementation

Middleware jsonBody() {
  return (Handler innerHandler) {
    return (Request request) async {
      if (request.method == 'GET' || request.method == 'HEAD') {
        return innerHandler(request);
      }

      final contentType = request.headers['content-type'] ?? '';
      if (!contentType.contains('application/json')) {
        return innerHandler(request);
      }

      final body = await request.readAsString();
      final json = body.isNotEmpty ? jsonDecode(body) : null;

      return innerHandler(request.change(context: {
        ...request.context,
        'body': json,
      }));
    };
  };
}