@@ -42,4 +42,81 @@ void main() {
42
42
equals ('$stringValue $intValue ' ),
43
43
);
44
44
});
45
+
46
+ test ('middleware can be used to read the request body' , () async {
47
+ Middleware requestValidator () {
48
+ return (handler) {
49
+ return (context) async {
50
+ final body = await context.request.body ();
51
+ if (body.isEmpty) return Response (statusCode: HttpStatus .badRequest);
52
+ return handler (context);
53
+ };
54
+ };
55
+ }
56
+
57
+ Future <Response > onRequest (RequestContext context) async {
58
+ final body = await context.request.body ();
59
+ return Response (body: 'body: $body ' );
60
+ }
61
+
62
+ final handler = const Pipeline ()
63
+ .addMiddleware (requestValidator ())
64
+ .addHandler (onRequest);
65
+
66
+ var request = Request .get (Uri .parse ('http://localhost/' ));
67
+ var context = _MockRequestContext ();
68
+ when (() => context.request).thenReturn (request);
69
+ var response = await handler (context);
70
+
71
+ expect (response.statusCode, equals (HttpStatus .badRequest));
72
+
73
+ const body = '__test_body__' ;
74
+ request = Request .get (Uri .parse ('http://localhost/' ), body: body);
75
+ context = _MockRequestContext ();
76
+ when (() => context.request).thenReturn (request);
77
+ response = await handler (context);
78
+
79
+ expect (response.statusCode, equals (HttpStatus .ok));
80
+ expect (await response.body (), equals ('body: $body ' ));
81
+ });
82
+
83
+ test ('middleware can be used to read the response body' , () async {
84
+ const emptyBody = '(empty)' ;
85
+ Middleware responseValidator () {
86
+ return (handler) {
87
+ return (context) async {
88
+ final response = await handler (context);
89
+ final body = await response.body ();
90
+ if (body.isEmpty) return Response (body: emptyBody);
91
+ return response;
92
+ };
93
+ };
94
+ }
95
+
96
+ Future <Response > onRequest (RequestContext context) async {
97
+ final body = await context.request.body ();
98
+ return Response (body: body);
99
+ }
100
+
101
+ final handler = const Pipeline ()
102
+ .addMiddleware (responseValidator ())
103
+ .addHandler (onRequest);
104
+
105
+ var request = Request .get (Uri .parse ('http://localhost/' ));
106
+ var context = _MockRequestContext ();
107
+ when (() => context.request).thenReturn (request);
108
+ var response = await handler (context);
109
+
110
+ expect (response.statusCode, equals (HttpStatus .ok));
111
+ expect (response.body (), completion (equals (emptyBody)));
112
+
113
+ const body = '__test_body__' ;
114
+ request = Request .get (Uri .parse ('http://localhost/' ), body: body);
115
+ context = _MockRequestContext ();
116
+ when (() => context.request).thenReturn (request);
117
+ response = await handler (context);
118
+
119
+ expect (response.statusCode, equals (HttpStatus .ok));
120
+ expect (response.body (), completion (equals (body)));
121
+ });
45
122
}
0 commit comments