aboutsummaryrefslogtreecommitdiff
path: root/lib/util/isar_handler.dart
blob: 734fe0fd47015c8e734e517be1de31949bfe6a19 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import 'package:isar/isar.dart';

import 'package:kulinar_app/models/recipe_class.dart';

/// Handles user data persistence related app storage
class IsarHandler {
  late Future<Isar> db;

  IsarHandler() {
    db = _openDB();
  }

  /// Stores the given `data` as a string with the `key`.
  Future<int> save(Recipe recipe) async {
    final isar = await db;
    return await isar.writeTxn<int>(() => isar.recipes.put(recipe));
  }

  /// Fetches all recipes
  Future<List<Recipe>> load() async {
    final isar = await db;
    return await isar.recipes.where().findAll();
  }

  /// Fetches the Recipe related to the given `title`.
  Future<Recipe?> fetch(String title) async {
    final isar = await db;
    return await isar.recipes.filter().titleEqualTo(title).findFirst();
  }

  Future clear() async {
    final isar = await db;
    return await isar.writeTxn(() => isar.recipes.clear());
  }

  Future<Isar> _openDB() async {
    if (Isar.instanceNames.isEmpty) {
      return await Isar.open(
        [RecipeSchema],
        inspector: true,
      );
    }

    return Future.value(Isar.getInstance());
  }
}