diff --git a/lib/src/http/services/memory.dart b/lib/src/http/services/memory.dart index 538c07f5..06a777f4 100644 --- a/lib/src/http/services/memory.dart +++ b/lib/src/http/services/memory.dart @@ -1,14 +1,23 @@ part of angel_framework.http; +/// Represents data that can be serialized into a MemoryService; +class MemoryModel { + int id; +} + /// An in-memory [Service]. class MemoryService extends Service { - Map items = {}; + Map items = {}; - _makeJson(int index, T t) { - if (T == null || T == Map) - return mergeMap([god.serializeObject(t), {'id': index}]); - else - return t; + MemoryService() :super() { + if (!reflectType(T).isAssignableTo(reflectType(MemoryModel))) { + throw new Exception( + "MemoryServices only support classes that inherit from MemoryModel."); + } + } + + _makeJson(int index, MemoryModel t) { + return t..id = index; } Future index([Map params]) async { @@ -21,7 +30,7 @@ class MemoryService extends Service { Future read(id, [Map params]) async { int desiredId = int.parse(id.toString()); if (items.containsKey(desiredId)) { - T found = items[desiredId]; + MemoryModel found = items[desiredId]; if (found != null) { return _makeJson(desiredId, found); } else throw new AngelHttpException.NotFound(); @@ -30,9 +39,12 @@ class MemoryService extends Service { Future create(data, [Map params]) async { //try { - var created = (data is Map) ? god.deserializeDatum(data, outputType: T) : data; - items[items.length] = created; - return _makeJson(items.length - 1, created); + MemoryModel created = (data is MemoryModel) ? data : god.deserializeDatum( + data, outputType: T); + + created.id = items.length; + items[created.id] = created; + return created; /*} catch (e) { throw new AngelHttpException.BadRequest(message: 'Invalid data.'); }*/ @@ -69,11 +81,9 @@ class MemoryService extends Service { Future remove(id, [Map params]) async { int desiredId = int.parse(id.toString()); if (items.containsKey(desiredId)) { - T item = items[desiredId]; + MemoryModel item = items[desiredId]; items[desiredId] = null; return _makeJson(desiredId, item); } else throw new AngelHttpException.NotFound(); } - - MemoryService() : super(); } \ No newline at end of file diff --git a/pubspec.yaml b/pubspec.yaml index 1bb11394..a0b77441 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -1,5 +1,5 @@ name: angel_framework -version: 1.0.0-dev+2 +version: 1.0.0-dev+3 description: Core libraries for the Angel framework. author: Tobe O homepage: https://github.com/angel-dart/angel_framework diff --git a/test/services.dart b/test/services.dart index 295e5812..d40d82e2 100644 --- a/test/services.dart +++ b/test/services.dart @@ -3,7 +3,7 @@ import 'package:http/http.dart' as http; import 'package:json_god/json_god.dart' as god; import 'package:test/test.dart'; -class Todo { +class Todo extends MemoryModel { String text; String over; }