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 : /// 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 : ///
21 : /// If the transformed channel emits invalid JSON, this emits a
22 : /// [FormatException]. If an unencodable object is added to the sink, it
23 : /// synchronously throws a [JsonUnsupportedObjectError].
24 : class JsonDocumentTransformer
25 : implements StreamChannelTransformer<Object, String> {
26 : /// The underlying codec that implements the encoding and decoding logic.
27 : final JsonCodec _codec;
28 :
29 : /// Creates a new transformer.
30 : ///
31 : /// The [reviver] and [toEncodable] arguments work the same way as the
32 : /// corresponding arguments to [new JsonCodec].
33 : JsonDocumentTransformer({reviver(key, value), toEncodable(object)})
34 0 : : _codec = new JsonCodec(reviver: reviver, toEncodable: toEncodable);
35 :
36 0 : JsonDocumentTransformer._(this._codec);
37 :
38 : StreamChannel bind(StreamChannel<String> channel) {
39 0 : var stream = channel.stream.map(_codec.decode);
40 0 : var sink = new StreamSinkTransformer.fromHandlers(handleData: (data, sink) {
41 0 : sink.add(_codec.encode(data));
42 0 : }).bind(channel.sink);
43 0 : return new StreamChannel.withCloseGuarantee(stream, sink);
44 : }
45 : }
|