From 82b32318e88f5b447d705543f6ea9890f110c589 Mon Sep 17 00:00:00 2001 From: Tobe O Date: Mon, 22 Oct 2018 12:18:10 -0400 Subject: [PATCH] Add service.map --- lib/src/core/anonymous_service.dart | 12 ++++++------ lib/src/core/service.dart | 28 ++++++++++++++++++++++++++++ 2 files changed, 34 insertions(+), 6 deletions(-) diff --git a/lib/src/core/anonymous_service.dart b/lib/src/core/anonymous_service.dart index 1d3117e2..2da73870 100644 --- a/lib/src/core/anonymous_service.dart +++ b/lib/src/core/anonymous_service.dart @@ -12,12 +12,12 @@ class AnonymousService extends Service { FutureOr Function(Id, Data, [Map]) _modify, _update; AnonymousService( - {FutureOr> index([Map params]), - FutureOr read(Id id, [Map params]), - FutureOr create(Data data, [Map params]), - FutureOr modify(Id id, Data data, [Map params]), - FutureOr update(Id id, Data data, [Map params]), - FutureOr remove(Id id, [Map params])}) + {FutureOr> index([Map params]), + FutureOr read(Id id, [Map params]), + FutureOr create(Data data, [Map params]), + FutureOr modify(Id id, Data data, [Map params]), + FutureOr update(Id id, Data data, [Map params]), + FutureOr remove(Id id, [Map params])}) : super() { _index = index; _read = read; diff --git a/lib/src/core/service.dart b/lib/src/core/service.dart index 7f6cb952..b6fc9e29 100644 --- a/lib/src/core/service.dart +++ b/lib/src/core/service.dart @@ -6,6 +6,7 @@ import 'package:angel_http_exception/angel_http_exception.dart'; import 'package:merge_map/merge_map.dart'; import '../util.dart'; +import 'anonymous_service.dart'; import 'hooked_service.dart' show HookedService; import 'metadata.dart'; import 'response_context.dart'; @@ -124,6 +125,33 @@ class Service extends Routable { throw new AngelHttpException.methodNotAllowed(); } + /// Creates an [AnonymousService] that wraps over this one, and maps input and output + /// using two converter functions. + /// + /// Handy utility for handling data in a type-safe manner. + Service map(U Function(Data) encoder, Data Function(U) decoder) { + return new AnonymousService( + index: ([params]) { + return index(params).then((it) => it.map(encoder).toList()); + }, + read: (id, [params]) { + return read(id, params).then(encoder); + }, + create: (data, [params]) { + return create(decoder(data), params).then(encoder); + }, + modify: (id, data, [params]) { + return modify(id, decoder(data), params).then(encoder); + }, + update: (id, data, [params]) { + return update(id, decoder(data), params).then(encoder); + }, + remove: (id, [params]) { + return remove(id, params).then(encoder); + }, + ); + } + /// Transforms an [id] (whether it is a String, num, etc.) into one acceptable by a service. /// /// The single type argument, [T], is used to determine how to parse the [id].