diff --git a/lib/src/core/request_context.dart b/lib/src/core/request_context.dart index 1afe206b..0d9c072b 100644 --- a/lib/src/core/request_context.dart +++ b/lib/src/core/request_context.dart @@ -221,14 +221,14 @@ abstract class RequestContext { /// Returns as `true` if the client's `Accept` header indicates that it will accept any response content type. bool get acceptsAll => _acceptsAllCache ??= accepts('*/*'); - /// Shorthand for deserializing a body. + /// Shorthand for deserializing [bodyAsMap], using some transformer function [f]. Future deserializeBody(FutureOr Function(Map) f, {Encoding encoding = utf8}) async { await parseBody(encoding: encoding); return await f(bodyAsMap); } - /// Shorthand for decoding a body. + /// Shorthand for decoding [bodyAsMap], using some [codec]. Future decodeBody(Codec codec, {Encoding encoding = utf8}) => deserializeBody(codec.decode, encoding: encoding); diff --git a/test/body_test.dart b/test/body_test.dart index 2f69b541..43051770 100644 --- a/test/body_test.dart +++ b/test/body_test.dart @@ -61,6 +61,14 @@ void main() { expect(req.bodyAsList, ['foo', 'bar']); }); + test('deserializeBody', () async { + var req = await request( + asJson: true, bodyFields: {'text': 'Hey', 'complete': false}); + var todo = await req.deserializeBody(Todo.fromMap); + expect(todo.text, 'Hey'); + expect(todo.completed, false); + }); + test('throws when body has not been parsed', () async { var req = await request(parse: false); expect(() => req.bodyAsObject, throwsStateError); @@ -97,3 +105,13 @@ void main() { throwsStateError); }); } + +class Todo { + String text; + bool completed; + + Todo({this.text, this.completed}); + + static Todo fromMap(Map m) => + Todo(text: m['text'] as String, completed: m['complete'] as bool); +}