Move MdYamlDoc loading to its own class

This commit is contained in:
Vishesh Handa
2020-03-14 23:32:29 +01:00
parent d87d873962
commit b0cc615aae
3 changed files with 73 additions and 5 deletions

View File

@ -0,0 +1,29 @@
import 'dart:io';
import 'package:gitjournal/core/md_yaml_doc.dart';
import 'package:gitjournal/core/md_yaml_doc_codec.dart';
class MdYamlDocLoader {
static final _serializer = MarkdownYAMLCodec();
Future<MdYamlDoc> loadDoc(String filePath) async {
// FIXME: What about parse errors?
final file = File(filePath);
if (!file.existsSync()) {
throw MdYamlDocNotFoundException(filePath);
}
final fileData = await file.readAsString();
var doc = _serializer.decode(fileData);
return doc;
}
}
class MdYamlDocNotFoundException implements Exception {
final String filePath;
MdYamlDocNotFoundException(this.filePath);
@override
String toString() => "MdYamlDocNotFoundException: $filePath";
}

View File

@ -1,6 +1,7 @@
import 'dart:io';
import 'package:fimber/fimber.dart';
import 'package:gitjournal/core/md_yaml_doc_loader.dart';
import 'package:gitjournal/core/note_notifier.dart';
import 'package:gitjournal/settings.dart';
import 'package:gitjournal/utils/markdown.dart';
@ -37,6 +38,8 @@ class Note with NotesNotifier {
String _summary;
static final _mdYamlDocLoader = MdYamlDocLoader();
Note(this.parent, this._filePath);
Note.newNote(this.parent) {
@ -149,16 +152,14 @@ class Note with NotesNotifier {
Fimber.d("Note modified: $_filePath");
}
if (!file.existsSync()) {
try {
data = await _mdYamlDocLoader.loadDoc(_filePath);
} on MdYamlDocNotFoundException catch (_) {
_loadState = NoteLoadState.NotExists;
_notifyModified();
return _loadState;
}
// FIXME: This could throw an exception!
final string = await file.readAsString();
data = _serializer.decode(string);
fileLastModified = file.lastModifiedSync();
_loadState = NoteLoadState.Loaded;

View File

@ -0,0 +1,38 @@
import 'dart:io';
import 'package:gitjournal/core/md_yaml_doc_loader.dart';
import 'package:path/path.dart' as p;
import 'package:test/test.dart';
void main() {
group('MdYamlDocLoader', () {
Directory tempDir;
String filePath;
var contents = """---
type: Journal
foo: bar
---
Alright.""";
setUpAll(() async {
tempDir = await Directory.systemTemp.createTemp('__doc_loader_test__');
filePath = p.join(tempDir.path, "doc0");
await File(filePath).writeAsString(contents);
});
tearDownAll(() async {
tempDir.deleteSync(recursive: true);
});
test('Should load one doc', () async {
var loader = MdYamlDocLoader();
var doc = await loader.loadDoc(filePath);
expect(doc.body, "Alright.");
expect(doc.props["type"], "Journal");
expect(doc.props["foo"], "bar");
expect(doc.props.length, 2);
});
});
}