Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 8 additions & 6 deletions packages/dart_frog/lib/src/request.dart
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ class Request {

Request._(this._request);

final shelf.Request _request;
shelf.Request _request;

/// Connection information for the associated HTTP request.
HttpConnectionInfo get connectionInfo {
Expand Down Expand Up @@ -146,12 +146,16 @@ class Request {

/// Returns a [Future] containing the body as a [String].
Future<String> body() async {
final bodyFromCache = _requestBodyCache[_request];
if (bodyFromCache != null) return bodyFromCache;
const requestBodyKey = 'dart_frog.request.body';
final bodyFromContext =
_request.context[requestBodyKey] as Completer<String>?;
if (bodyFromContext != null) return bodyFromContext.future;

final completer = Completer<String>();
try {
_requestBodyCache[_request] = completer.future;
_request = _request.change(
context: {..._request.context, requestBodyKey: completer},
);
completer.complete(await _request.readAsString());
} catch (error, stackTrace) {
completer.completeError(error, stackTrace);
Expand Down Expand Up @@ -180,5 +184,3 @@ class Request {
return Request._(_request.change(headers: headers, path: path, body: body));
}
}

final _requestBodyCache = Expando<Future<String>>('dart_frog.request.body');
34 changes: 34 additions & 0 deletions packages/dart_frog/test/src/serve_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,40 @@ void main() {
await server.close();
});

test('can read request.body across middleware:handler gap', () async {
Middleware middleware() {
return (handler) {
return (context) async {
await context.request.body(); // Read #1
return handler(context);
};
};
}

Handler handler() {
return (context) async {
await context.request.body(); // Read #2
return Response();
};
}

const address = 'localhost';
const port = 3002;
final pipeline = const Pipeline().addMiddleware(middleware());
final router = Router()..mount('/', handler());
final server = await serve(
pipeline.addHandler(router.call),
address,
port,
);
final client = HttpClient();
final request = await client.getUrl(Uri.parse('http://$address:$port'));
final response = await request.close();
expect(response.statusCode, equals(HttpStatus.ok));
client.close();
await server.close();
});

test('exposes connectionInfo on the incoming request', () async {
late HttpConnectionInfo connectionInfo;
final server = await serve(
Expand Down