-
Notifications
You must be signed in to change notification settings - Fork 159
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Architecture/data layer #8
Merged
Merged
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
c44ee8e
Adds `meta` and `equatable` package dependencies (both null-safe)
matuella b3728f3
Adds `DatabaseRepository` abstract class
matuella fc6c6b7
Adds `sembast`, `uuid`, `path` and `path_provider` dependencies (all …
matuella de2a62d
Adds `DatabaseRepository` implementation with `sembast`
matuella 2f1270b
Adds `openDatabase` (sembast) function and a placeholder for future m…
matuella b0ded88
Adds `shouldMerge` to `DatabaseRepository.put`
matuella 189f6db
Exposes core private functionality in data layer, while annotating wi…
matuella 080ee53
Adds `mocktail` testing dependency
matuella c47a092
Adds `DatabaseRepositoryImpl` tests
matuella 83fc9b1
Adds `applyMigration` placeholder test
matuella File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,157 @@ | ||
import 'dart:async'; | ||
|
||
import 'package:equatable/equatable.dart'; | ||
import 'package:meta/meta.dart'; | ||
import 'package:sembast/sembast.dart'; | ||
|
||
/// Handles the local persistence to the database | ||
abstract class DatabaseRepository { | ||
/// Adds an [object] to the [store], using a [serializer] | ||
/// | ||
/// If there is already an object with the same [KeyStorable.id], the default behavior is to merge all of its fields. | ||
/// [shouldMerge] should be `false` if pre-existing fields should not be merged. | ||
Future<void> put<T extends KeyStorable>({ | ||
required T object, | ||
required JsonSerializer<T> serializer, | ||
required DatabaseStore store, | ||
bool shouldMerge = true, | ||
}); | ||
|
||
/// Deletes the value with [key] from the [store] | ||
Future<void> removeObject({required String key, required DatabaseStore store}); | ||
|
||
/// Retrieves an object with [key] from the [store] | ||
/// | ||
/// Returns `null` if the key doesn't exist | ||
Future<T?> getObject<T extends KeyStorable>({ | ||
required String key, | ||
required JsonSerializer<T> serializer, | ||
required DatabaseStore store, | ||
}); | ||
|
||
/// Retrieves all objects within [store] | ||
Future<List<T>> getAll<T extends KeyStorable>({ | ||
required JsonSerializer<T> serializer, | ||
required DatabaseStore store, | ||
}); | ||
|
||
/// Retrieves a stream of all the [store] objects, triggered whenever any update occurs to this [store] | ||
Future<Stream<List<T>>> listenAll<T extends KeyStorable>({ | ||
required JsonSerializer<T> serializer, | ||
required DatabaseStore store, | ||
}); | ||
} | ||
|
||
enum DatabaseStore { | ||
decks, | ||
cards, | ||
executions, | ||
resources, | ||
} | ||
|
||
/// Middleware that should be responsible of parsing a type [T] to/from a JSON representation | ||
abstract class JsonSerializer<T extends Object> { | ||
T fromMap(Map<String, dynamic> json); | ||
Map<String, dynamic> mapOf(T object); | ||
} | ||
|
||
/// Base class that adds a key [id] to allow its implementation to be stored/identified in any database | ||
abstract class KeyStorable extends Equatable { | ||
const KeyStorable({required this.id}); | ||
final String id; | ||
} | ||
|
||
// | ||
// DatabaseRepository implementation using `sembast` | ||
// | ||
class DatabaseRepositoryImpl implements DatabaseRepository { | ||
DatabaseRepositoryImpl(this._db); | ||
|
||
// `sembast` database instance | ||
final Database _db; | ||
|
||
@override | ||
Future<void> put<T extends KeyStorable>({ | ||
required T object, | ||
required JsonSerializer<T> serializer, | ||
required DatabaseStore store, | ||
bool shouldMerge = true, | ||
}) async { | ||
final storeMap = stringMapStoreFactory.store(store.key); | ||
final deserializedObject = serializer.mapOf(object); | ||
|
||
await storeMap.record(object.id).put(_db, deserializedObject, merge: shouldMerge); | ||
} | ||
|
||
@override | ||
Future<void> removeObject({required String key, required DatabaseStore store}) async { | ||
final storeMap = stringMapStoreFactory.store(store.key); | ||
await storeMap.record(key).delete(_db); | ||
} | ||
|
||
@override | ||
Future<T?> getObject<T extends KeyStorable>({ | ||
required String key, | ||
required JsonSerializer<T> serializer, | ||
required DatabaseStore store, | ||
}) async { | ||
final storeMap = stringMapStoreFactory.store(store.key); | ||
final rawObject = await storeMap.record(key).get(_db); | ||
|
||
if (rawObject != null) { | ||
return serializer.fromMap(rawObject); | ||
} | ||
|
||
return null; | ||
} | ||
|
||
@override | ||
Future<List<T>> getAll<T extends KeyStorable>({ | ||
required JsonSerializer<T> serializer, | ||
required DatabaseStore store, | ||
}) async { | ||
final storeMap = stringMapStoreFactory.store(store.key); | ||
|
||
final allRecords = await storeMap.find(_db); | ||
|
||
return allRecords.map((record) => serializer.fromMap(record.value)).toList(); | ||
} | ||
|
||
@override | ||
Future<Stream<List<T>>> listenAll<T extends KeyStorable>({ | ||
required JsonSerializer<T> serializer, | ||
required DatabaseStore store, | ||
}) async { | ||
final storeMap = stringMapStoreFactory.store(store.key); | ||
|
||
final transformer = _snapshotSerializerTransformer(serializer); | ||
return storeMap.query().onSnapshots(_db).transform(transformer); | ||
} | ||
|
||
/// Transforms a list of `sembast` snapshot records into a list of objects parsed by [serializer] | ||
StreamTransformer<List<RecordSnapshot<String, Map<String, Object?>>>, List<T>> | ||
_snapshotSerializerTransformer<T extends Object>(JsonSerializer<T> serializer) { | ||
return StreamTransformer.fromHandlers( | ||
handleData: (snapshots, sink) { | ||
final transformedRecords = snapshots.map((record) => serializer.fromMap(record.value)).toList(); | ||
sink.add(transformedRecords); | ||
}, | ||
); | ||
} | ||
} | ||
|
||
extension StoreKeys on DatabaseStore { | ||
@visibleForTesting | ||
String get key { | ||
switch (this) { | ||
matuella marked this conversation as resolved.
Show resolved
Hide resolved
|
||
case DatabaseStore.decks: | ||
return 'decks'; | ||
case DatabaseStore.cards: | ||
return 'cards'; | ||
case DatabaseStore.executions: | ||
return 'card_executions'; | ||
case DatabaseStore.resources: | ||
return 'resources'; | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,37 @@ | ||
import 'dart:async'; | ||
|
||
import 'package:flutter/foundation.dart'; | ||
import 'package:path/path.dart' as path; | ||
import 'package:path_provider/path_provider.dart'; | ||
import 'package:sembast/sembast.dart'; | ||
import 'package:sembast/sembast_io.dart'; | ||
|
||
const _schemaVersion = 1; | ||
const _dbName = 'memo_sembast.db'; | ||
|
||
/// Opens this application's [Database], creating a new one if nonexistent | ||
Future<Database> openDatabase() async { | ||
final dir = await getApplicationDocumentsDirectory(); | ||
// Make sure that the application documents directory exists | ||
await dir.create(recursive: true); | ||
|
||
final dbPath = path.join(dir.path, _dbName); | ||
|
||
return databaseFactoryIo.openDatabase(dbPath, version: _schemaVersion, onVersionChanged: applyMigrations); | ||
} | ||
|
||
@visibleForTesting | ||
Future<void> applyMigrations(Database db, int oldVersion, int newVersion) async { | ||
// Call the necessary migrations in order | ||
} | ||
|
||
// | ||
// Migrations | ||
// | ||
|
||
// Example: | ||
// Future<void> migrateToVersion2(Database db) async { | ||
// final store = stringMapStoreFactory.store('storeThatNeedsMigration'); | ||
// final updatableItemsFinder = Finder(filter: Filter.equals('myUpdatedField', 1)); | ||
// await store.update(db, { 'myUpdatedField': 2 }, finder: updatableItemsFinder); | ||
// } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Maybe creating a single or multiple custom types to this return? This function signature is unreadable
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
There is no way to create custom types that aren't functions. This might be possible in 2.13, but not right now