|
| 1 | +import 'package:json_api/document.dart'; |
| 2 | + |
| 3 | +import 'model.dart'; |
| 4 | + |
| 5 | +abstract class DAO<T extends HasId> { |
| 6 | + final collection = <String, T>{}; |
| 7 | + |
| 8 | + int get length => collection.length; |
| 9 | + |
| 10 | + Resource toResource(T t); |
| 11 | + |
| 12 | + Relationship relationship(String name, T t) { |
| 13 | + throw ArgumentError(); |
| 14 | + } |
| 15 | + |
| 16 | + Map<String, Relationship> relationships(List<String> names, T t) => |
| 17 | + Map.fromIterables(names, names.map((_) => relationship(_, t))); |
| 18 | + |
| 19 | + T fetchById(String id) => collection[id]; |
| 20 | + |
| 21 | + void insert(T t) => collection[t.id] = t; |
| 22 | + |
| 23 | + Iterable<T> fetchCollection({int offset = 0, int limit = 1}) => |
| 24 | + collection.values.skip(offset).take(limit); |
| 25 | + |
| 26 | + HasId fromResource(Resource r); |
| 27 | + |
| 28 | + addRelationship(T t, String name, HasId related) {} |
| 29 | +} |
| 30 | + |
| 31 | +class CarDAO extends DAO<Car> { |
| 32 | + Resource toResource(Car _) => |
| 33 | + Resource('cars', _.id, attributes: {'name': _.name}); |
| 34 | + |
| 35 | + @override |
| 36 | + HasId fromResource(Resource r) => Car(r.id, r.attributes['name']); |
| 37 | +} |
| 38 | + |
| 39 | +class CityDAO extends DAO<City> { |
| 40 | + Resource toResource(City _) => |
| 41 | + Resource('cities', _.id, attributes: {'name': _.name}); |
| 42 | + |
| 43 | + @override |
| 44 | + HasId fromResource(Resource r) => City(r.id, r.attributes['name']); |
| 45 | +} |
| 46 | + |
| 47 | +class BrandDAO extends DAO<Brand> { |
| 48 | + Resource toResource(Brand brand) => Resource('brands', brand.id, |
| 49 | + attributes: {'name': brand.name}, |
| 50 | + relationships: relationships(['headquarters', 'models'], brand)); |
| 51 | + |
| 52 | + Relationship relationship(String name, Brand brand) { |
| 53 | + switch (name) { |
| 54 | + case 'headquarters': |
| 55 | + return ToOne(brand.headquarters == null |
| 56 | + ? null |
| 57 | + : Identifier('cities', brand.headquarters)); |
| 58 | + case 'models': |
| 59 | + return ToMany(brand.models.map((_) => Identifier('cars', _))); |
| 60 | + } |
| 61 | + throw ArgumentError(); |
| 62 | + } |
| 63 | + |
| 64 | + @override |
| 65 | + HasId fromResource(Resource r) => Brand(r.id, r.attributes['name']); |
| 66 | + |
| 67 | + @override |
| 68 | + addRelationship(Brand obj, String name, HasId related) { |
| 69 | + switch (name) { |
| 70 | + case 'models': |
| 71 | + obj.models.add(related.id); |
| 72 | + break; |
| 73 | + default: |
| 74 | + throw ArgumentError.value(name, 'name'); |
| 75 | + } |
| 76 | + } |
| 77 | +} |
0 commit comments