OLD | NEW |
---|---|
(Empty) | |
1 // Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file | |
2 // for details. All rights reserved. Use of this source code is governed by a | |
3 // BSD-style license that can be found in the LICENSE file. | |
4 | |
5 library shelf.body; | |
6 | |
7 import 'dart:async'; | |
8 import 'dart:convert'; | |
9 | |
10 /// The body of a request or response. | |
11 /// | |
12 /// This tracks whether the body has been read. It's separate from [Message] | |
13 /// because the message may be changed with [Message.change], but each instance | |
14 /// should share a notion of whether the body was read. | |
15 class Body { | |
16 /// The contents of the message body. | |
17 final Stream<List<int>> _stream; | |
18 | |
19 /// Whether [_body] has been read. | |
20 /// | |
21 /// After calling [read], this will be `true`. | |
22 bool _wasRead = false; | |
Bob Nystrom
2015/08/31 21:05:32
How about just making _stream writable, and settin
nweiz
2015/08/31 21:16:05
Done.
| |
23 | |
24 Body._(this._stream); | |
25 | |
26 /// Converts [body] to a byte stream and wraps it in a [Body]. | |
27 /// | |
28 /// [body] may be either a [Body], a [String], a [Stream<List<int>>], or | |
29 /// `null`. If it's a [String], [encoding] will be used to convert it to a | |
30 /// [Stream<List<int>>]. | |
31 factory Body(body, [Encoding encoding]) { | |
32 if (encoding == null) encoding = UTF8; | |
33 | |
34 if (body is Body) return body; | |
Bob Nystrom
2015/08/31 21:05:32
This means doing new Body(previouslyReadBody) does
nweiz
2015/08/31 21:16:05
Yeah, I think that matches the expected semantics
| |
35 | |
Bob Nystrom
2015/08/31 21:05:32
Should this throw if an encoding is prodivided but
nweiz
2015/08/31 21:16:04
I think it's probably fine. Definitely not worth
| |
36 var stream; | |
37 if (body == null) { | |
38 stream = new Stream.fromIterable([]); | |
39 } else if (body is String) { | |
40 stream = new Stream.fromIterable([encoding.encode(body)]); | |
41 } else if (body is Stream) { | |
42 stream = body; | |
43 } else { | |
44 throw new ArgumentError('Response body "$body" must be a String or a ' | |
45 'Stream.'); | |
46 } | |
47 | |
48 return new Body._(stream); | |
49 } | |
50 | |
51 /// Returns a [Stream] representing the body. | |
52 /// | |
53 /// Can only be called once. | |
54 Stream<List<int>> read() { | |
55 if (_wasRead) { | |
56 throw new StateError("The 'read' method can only be called once on a " | |
57 "shelf.Request/shelf.Response object."); | |
58 } | |
59 _wasRead = true; | |
60 return _stream; | |
61 } | |
62 } | |
OLD | NEW |