78 lines
1.9 KiB
Dart
78 lines
1.9 KiB
Dart
import 'package:notas/data/app_database.dart';
|
|
import 'package:notas/models/note.dart';
|
|
|
|
class NoteRepository {
|
|
NoteRepository({required AppDatabase database}) : _database = database;
|
|
|
|
final AppDatabase _database;
|
|
|
|
Future<List<Note>> loadNotes() async {
|
|
return _loadNotesFromDatabase();
|
|
}
|
|
|
|
Future<Note> createNote(Note note) async {
|
|
final int id = await _database.insertNoteAtTop(
|
|
NotesCompanion.insert(
|
|
title: note.title,
|
|
body: note.body,
|
|
createdAt: note.createdAt,
|
|
updatedAt: note.updatedAt,
|
|
sortIndex: 0,
|
|
),
|
|
);
|
|
|
|
return note.copyWith(id: id, index: 0);
|
|
}
|
|
|
|
Future<Note> updateNote(Note note) async {
|
|
final int noteId = note.id ?? (throw ArgumentError('Note id is required to update a note.'));
|
|
|
|
await _database.updateNoteRow(
|
|
DbNote(
|
|
id: noteId,
|
|
title: note.title,
|
|
body: note.body,
|
|
createdAt: note.createdAt,
|
|
updatedAt: note.updatedAt,
|
|
sortIndex: note.index,
|
|
),
|
|
);
|
|
|
|
return note;
|
|
}
|
|
|
|
Future<void> deleteNote(Note note) async {
|
|
final int noteId = note.id ?? (throw ArgumentError('Note id is required to delete a note.'));
|
|
|
|
await _database.deleteNoteAndShift(
|
|
id: noteId,
|
|
removedIndex: note.index,
|
|
);
|
|
}
|
|
|
|
Future<void> moveNote(Note note, int newIndex) async {
|
|
final int noteId = note.id ?? (throw ArgumentError('Note id is required to reorder a note.'));
|
|
|
|
await _database.moveNote(
|
|
id: noteId,
|
|
oldIndex: note.index,
|
|
newIndex: newIndex,
|
|
);
|
|
}
|
|
|
|
Future<List<Note>> _loadNotesFromDatabase() async {
|
|
final List<DbNote> rows = await _database.getAllNotes();
|
|
return rows.map(_fromRow).toList();
|
|
}
|
|
|
|
Note _fromRow(DbNote row) {
|
|
return Note(
|
|
id: row.id,
|
|
title: row.title,
|
|
body: row.body,
|
|
createdAt: row.createdAt,
|
|
updatedAt: row.updatedAt,
|
|
index: row.sortIndex,
|
|
);
|
|
}
|
|
} |