Add service.map
This commit is contained in:
parent
8ef86f61a3
commit
82b32318e8
2 changed files with 34 additions and 6 deletions
|
@ -12,12 +12,12 @@ class AnonymousService<Id, Data> extends Service<Id, Data> {
|
|||
FutureOr<Data> Function(Id, Data, [Map<String, dynamic>]) _modify, _update;
|
||||
|
||||
AnonymousService(
|
||||
{FutureOr<List<Data>> index([Map params]),
|
||||
FutureOr<Data> read(Id id, [Map params]),
|
||||
FutureOr<Data> create(Data data, [Map params]),
|
||||
FutureOr<Data> modify(Id id, Data data, [Map params]),
|
||||
FutureOr<Data> update(Id id, Data data, [Map params]),
|
||||
FutureOr<Data> remove(Id id, [Map params])})
|
||||
{FutureOr<List<Data>> index([Map<String, dynamic> params]),
|
||||
FutureOr<Data> read(Id id, [Map<String, dynamic> params]),
|
||||
FutureOr<Data> create(Data data, [Map<String, dynamic> params]),
|
||||
FutureOr<Data> modify(Id id, Data data, [Map<String, dynamic> params]),
|
||||
FutureOr<Data> update(Id id, Data data, [Map<String, dynamic> params]),
|
||||
FutureOr<Data> remove(Id id, [Map<String, dynamic> params])})
|
||||
: super() {
|
||||
_index = index;
|
||||
_read = read;
|
||||
|
|
|
@ -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<Id, Data> 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<Id, U> map<U>(U Function(Data) encoder, Data Function(U) decoder) {
|
||||
return new AnonymousService<Id, U>(
|
||||
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].
|
||||
|
|
Loading…
Reference in a new issue