69 lines
2.3 KiB
Dart
69 lines
2.3 KiB
Dart
import 'package:hive_ce_flutter/hive_flutter.dart';
|
|
import 'package:logger/logger.dart';
|
|
import '/models/category.dart';
|
|
import '/models/tag.dart';
|
|
import '/models/transaction_record.dart';
|
|
import '/utils/category_utils.dart';
|
|
import '/utils/tag_utils.dart';
|
|
import '/utils/transaction_utils.dart';
|
|
|
|
final _logger = Logger();
|
|
|
|
class HiveService {
|
|
static const String _categoryBox = 'categories';
|
|
static const String _tagBox = 'tags';
|
|
static const String _transactionBox = 'transactions';
|
|
|
|
static Future<void> init() async {
|
|
_logger.i('Initializing Hive database');
|
|
await Hive.initFlutter();
|
|
|
|
// Регистрация адаптеров
|
|
if (!Hive.isAdapterRegistered(CategoryAdapter().typeId)) {
|
|
Hive.registerAdapter(CategoryAdapter());
|
|
}
|
|
if (!Hive.isAdapterRegistered(TagAdapter().typeId)) {
|
|
Hive.registerAdapter(TagAdapter());
|
|
}
|
|
if (!Hive.isAdapterRegistered(TransactionRecordAdapter().typeId)) {
|
|
Hive.registerAdapter(TransactionRecordAdapter());
|
|
}
|
|
|
|
// Открытие всех Box'ов
|
|
await Future.wait([
|
|
Hive.openBox<Category>(_categoryBox),
|
|
Hive.openBox<Tag>(_tagBox),
|
|
Hive.openBox<TransactionRecord>(_transactionBox),
|
|
]);
|
|
|
|
// Проверка и заполнение начальными данными
|
|
await _checkAndFillInitialData();
|
|
}
|
|
|
|
static Box<Category> get categories => Hive.box<Category>(_categoryBox);
|
|
static Box<Tag> get tags => Hive.box<Tag>(_tagBox);
|
|
static Box<TransactionRecord> get transactions =>
|
|
Hive.box<TransactionRecord>(_transactionBox);
|
|
|
|
/// Проверяет и заполняет боксы начальными данными при первом запуске
|
|
static Future<void> _checkAndFillInitialData() async {
|
|
final catBox = categories;
|
|
if (catBox.isEmpty) {
|
|
_logger.i('Filling initial categories');
|
|
await catBox.addAll(CategoryUtils.getDefaultCategories());
|
|
}
|
|
|
|
final tagBox = tags;
|
|
if (tagBox.isEmpty) {
|
|
_logger.i('Filling initial tags');
|
|
await tagBox.addAll(TagUtils.getDefaultTags());
|
|
}
|
|
|
|
final transactionBox = transactions;
|
|
if (transactionBox.isEmpty) {
|
|
_logger.i('Filling sample transactions');
|
|
await transactionBox.addAll(TransactionUtils.getSampleTransactions());
|
|
}
|
|
}
|
|
}
|