OLD | NEW |
(Empty) | |
| 1 // Copyright (c) 2016, 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 import 'dart:convert'; |
| 6 |
| 7 import 'package:async/async.dart'; |
| 8 |
| 9 import '../stream_channel.dart'; |
| 10 import 'stream_channel_transformer.dart'; |
| 11 |
| 12 /// The canonical instance of [JsonDocumentTransformer]. |
| 13 final jsonDocument = new JsonDocumentTransformer(); |
| 14 |
| 15 /// A [StreamChannelTransformer] that transforms JSON documents—strings that |
| 16 /// contain individual objects encoded as JSON—into decoded Dart objects. |
| 17 /// |
| 18 /// This decodes JSON that's emitted by the transformed channel's stream, and |
| 19 /// encodes objects so that JSON is passed to the transformed channel's sink. |
| 20 class JsonDocumentTransformer |
| 21 implements StreamChannelTransformer<String, Object> { |
| 22 /// The underlying codec that implements the encoding and decoding logic. |
| 23 final JsonCodec _codec; |
| 24 |
| 25 /// Creates a new transformer. |
| 26 /// |
| 27 /// The [reviver] and [toEncodable] arguments work the same way as the |
| 28 /// corresponding arguments to [new JsonCodec]. |
| 29 JsonDocumentTransformer({reviver(key, value), toEncodable(object)}) |
| 30 : _codec = new JsonCodec(reviver: reviver, toEncodable: toEncodable); |
| 31 |
| 32 JsonDocumentTransformer._(this._codec); |
| 33 |
| 34 StreamChannel bind(StreamChannel<String> channel) { |
| 35 var stream = channel.stream.map(_codec.decode); |
| 36 var sink = new StreamSinkTransformer.fromHandlers(handleData: (data, sink) { |
| 37 sink.add(_codec.encode(data)); |
| 38 }).bind(channel.sink); |
| 39 return new StreamChannel(stream, sink); |
| 40 } |
| 41 } |
OLD | NEW |