semDbMgrBase.dart 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import 'package:sembast/sembast_io.dart';
  2. import 'dart:async';
  3. abstract class SemDbMgrBase<T> {
  4. final Database database;
  5. abstract final String repositoryName;
  6. SemDbMgrBase(this.database);
  7. // 获取存储
  8. StoreRef<String, Map<String, dynamic>> get storeRef {
  9. return StoreRef<String, Map<String, dynamic>>(repositoryName);
  10. }
  11. // 转换对象为Map
  12. Map<String, dynamic> toMap(T item);
  13. // 从Map创建对象
  14. T fromMap(Map<String, dynamic> map) {
  15. // 有些情况下存储的数据并不足以创建实例,此时子类不实现 fromMap 而是新建一个附带更多参数的接口
  16. // 注意此时 getAll 和 getById 等依赖 fromMap 的函数也不要使用,否则会抛出异常
  17. throw UnimplementedError('fromMap is not implemented for this repository');
  18. }
  19. // 添加或更新记录
  20. Future<String> addOrUpdate(T item, {String? id}) async {
  21. final itemMap = toMap(item);
  22. final recordId = id ?? DateTime.now().millisecondsSinceEpoch.toString();
  23. await storeRef.record(recordId).put(database, itemMap);
  24. return recordId;
  25. }
  26. // 获取所有记录
  27. Future<List<T>> getAll() async {
  28. final records = await storeRef.find(database);
  29. return records.map((record) => fromMap(record.value)).toList();
  30. }
  31. // 根据ID获取记录
  32. Future<T?> getById(String id) async {
  33. final record = await storeRef.record(id).get(database);
  34. return record != null ? fromMap(record) : null;
  35. }
  36. // 删除记录
  37. Future<void> delete(String id) async {
  38. await storeRef.record(id).delete(database);
  39. }
  40. // 清空存储
  41. Future<void> clear() async {
  42. await storeRef.delete(database);
  43. }
  44. }