Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(1011)

Unified Diff: lib/src/json_document_transformer.dart

Issue 1643843002: Add a document-by-document JSON transformer. (Closed) Base URL: git@github.com:dart-lang/stream_channel.git@master
Patch Set: Created 4 years, 11 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View side-by-side diff with in-line comments
Download patch
« no previous file with comments | « no previous file | lib/stream_channel.dart » ('j') | no next file with comments »
Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
Index: lib/src/json_document_transformer.dart
diff --git a/lib/src/json_document_transformer.dart b/lib/src/json_document_transformer.dart
new file mode 100644
index 0000000000000000000000000000000000000000..8d8dcce231b68cbdbe14b8bc308491a700ced464
--- /dev/null
+++ b/lib/src/json_document_transformer.dart
@@ -0,0 +1,41 @@
+// Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file
+// for details. All rights reserved. Use of this source code is governed by a
+// BSD-style license that can be found in the LICENSE file.
+
+import 'dart:convert';
+
+import 'package:async/async.dart';
+
+import '../stream_channel.dart';
+import 'stream_channel_transformer.dart';
+
+/// The canonical instance of [JsonDocumentTransformer].
+final jsonDocument = new JsonDocumentTransformer();
+
+/// A [StreamChannelTransformer] that transforms JSON documents—strings that
+/// contain individual objects encoded as JSON—into decoded Dart objects.
+///
+/// This decodes JSON that's emitted by the transformed channel's stream, and
+/// encodes objects so that JSON is passed to the transformed channel's sink.
+class JsonDocumentTransformer
+ implements StreamChannelTransformer<String, Object> {
+ /// The underlying codec that implements the encoding and decoding logic.
+ final JsonCodec _codec;
+
+ /// Creates a new transformer.
+ ///
+ /// The [reviver] and [toEncodable] arguments work the same way as the
+ /// corresponding arguments to [new JsonCodec].
+ JsonDocumentTransformer({reviver(key, value), toEncodable(object)})
+ : _codec = new JsonCodec(reviver: reviver, toEncodable: toEncodable);
+
+ JsonDocumentTransformer._(this._codec);
+
+ StreamChannel bind(StreamChannel<String> channel) {
+ var stream = channel.stream.map(_codec.decode);
+ var sink = new StreamSinkTransformer.fromHandlers(handleData: (data, sink) {
+ sink.add(_codec.encode(data));
+ }).bind(channel.sink);
+ return new StreamChannel(stream, sink);
+ }
+}
« no previous file with comments | « no previous file | lib/stream_channel.dart » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698