diff --git a/.gitignore b/.gitignore index 607fc424..e3978899 100644 --- a/.gitignore +++ b/.gitignore @@ -60,3 +60,4 @@ com_crashlytics_export_strings.xml crashlytics.properties crashlytics-build.properties fabric.properties +.dart_tool \ No newline at end of file diff --git a/lib/src/serializer.dart b/lib/src/serializer.dart new file mode 100644 index 00000000..925c1f73 --- /dev/null +++ b/lib/src/serializer.dart @@ -0,0 +1,24 @@ +import 'dart:async'; +import 'package:angel_framework/angel_framework.dart'; + +/// A middleware that enables the caching of response serialization. +/// +/// This can improve the performance of sending objects that are complex to serialize. +/// +/// You can pass a [shouldCache] callback to determine which values should be cached. +RequestHandler cacheSerializationResults( + {Duration timeout, FutureOr Function(RequestContext, ResponseContext, Object) shouldCache}) { + return (RequestContext req, ResponseContext res) async { + var oldSerializer = res.serializer; + var cache = {}; + res.serializer = (value) { + if (shouldCache == null) { + return cache.putIfAbsent(value, () => oldSerializer(value)); + } + + return oldSerializer(value); + }; + + return true; + }; +}