Line data Source code
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 : /// A [StreamChannelTransformer] that transforms JSON documents—strings that 13 : /// contain individual objects encoded as JSON—into decoded Dart objects. 14 : /// 15 : /// This decodes JSON that's emitted by the transformed channel's stream, and 16 : /// encodes objects so that JSON is passed to the transformed channel's sink. 17 : /// 18 : /// If the transformed channel emits invalid JSON, this emits a 19 : /// [FormatException]. If an unencodable object is added to the sink, it 20 : /// synchronously throws a [JsonUnsupportedObjectError]. 21 0 : final StreamChannelTransformer<Object?, String> jsonDocument = 22 : const _JsonDocument(); 23 : 24 : class _JsonDocument implements StreamChannelTransformer<Object?, String> { 25 11 : const _JsonDocument(); 26 : 27 0 : @override 28 : StreamChannel<Object?> bind(StreamChannel<String> channel) { 29 0 : var stream = channel.stream.map(jsonDecode); 30 0 : var sink = StreamSinkTransformer<Object, String>.fromHandlers( 31 0 : handleData: (data, sink) { 32 0 : sink.add(jsonEncode(data)); 33 0 : }).bind(channel.sink); 34 0 : return StreamChannel.withCloseGuarantee(stream, sink); 35 : } 36 : }