Commit ecb7ba0

derdilla <82763757+NobodyForNothing@users.noreply.github.com>
2024-03-28 11:39:30
extract castable extension
Signed-off-by: derdilla <82763757+NobodyForNothing@users.noreply.github.com>
1 parent 1def5b1
Changed files (4)
health_data_store
health_data_store/lib/src/extensions/castable.dart
@@ -0,0 +1,8 @@
+/// Extension for safer casting of generic objects.
+extension Castable on Object {
+  /// Returns null if this is not of type [T] else return casted object.
+  T? castOrNull<T>() {
+    if (this is T) return this as T;
+    return null;
+  }
+}
health_data_store/lib/src/repositories/medicine_intake_repository.dart
@@ -53,6 +53,7 @@ class MedicineIntakeRepository extends Repository<MedicineIntake> {
 
   @override
   Future<List<MedicineIntake>> get(DateRange range) async {
+    // TODO: change left join to join
     final results = await _db.rawQuery(
       'SELECT t.timestampUnixS, dosis, defaultDose, designation, color '
         'FROM Timestamps AS t '
health_data_store/lib/src/repositories/medicine_repository.dart
@@ -1,4 +1,5 @@
 import 'package:health_data_store/src/database_manager.dart';
+import 'package:health_data_store/src/extensions/castable.dart';
 import 'package:health_data_store/src/types/medicine.dart';
 import 'package:health_data_store/src/types/medicine_intake.dart';
 import 'package:sqflite_common/sqflite.dart';
@@ -59,10 +60,3 @@ class MedicineRepository {
   );
 
 }
-
-extension _Castable on Object {
-  T? castOrNull<T>() {
-    if (this is T) return this as T;
-    return null;
-  }
-}
health_data_store/test/src/extensions/castable_test.dart
@@ -0,0 +1,15 @@
+import 'package:health_data_store/src/extensions/castable.dart';
+import 'package:test/expect.dart';
+import 'package:test/scaffolding.dart';
+
+void main() {
+  test('should cast null to null', () {
+    expect((null as Object?)?.castOrNull<String>(), null);
+  });
+  test('should cast int', () {
+    expect((123 as Object?)?.castOrNull<int>(), 123);
+  });
+  test('should not cast incorrectly', () {
+    expect((123 as Object?)?.castOrNull<double>(), null);
+  });
+}