Files
GitJournal/lib/storage/serializers.dart
Vishesh Handa d6c2d5d05a Note id: Default to created and do not save if not required
For this journaling app, even though we are treating journal entries as
notes, we don't really any 'id'. Just the filename is quite adequate. In
the future, we can figure out this 'id' nonsense, and if it is even
required given that we're always going to be built on top of a FS.
2019-01-15 21:41:39 +01:00

76 lines
1.6 KiB
Dart

import 'dart:convert';
import 'package:yaml/yaml.dart';
import 'package:journal/note.dart';
abstract class NoteSerializer {
String encode(Note note);
Note decode(String str);
}
class JsonNoteSerializer implements NoteSerializer {
@override
Note decode(String str) {
final json = JsonDecoder().convert(str);
return new Note.fromJson(json);
}
@override
String encode(Note note) {
return JsonEncoder().convert(note.toJson());
}
}
class MarkdownYAMLSerializer implements NoteSerializer {
@override
Note decode(String str) {
if (str.startsWith("---\n")) {
var parts = str.split("---\n");
var yamlMap = loadYaml(parts[1]);
Map<String, dynamic> map = new Map<String, dynamic>();
yamlMap.forEach((key, value) {
map[key] = value;
});
map['body'] = parts[2].trimLeft();
return new Note.fromJson(map);
}
return new Note(body: str);
}
@override
String encode(Note note) {
const serparator = '---\n';
var str = "";
str += serparator;
var metadata = note.toJson();
metadata.remove('body');
// Do not save the 'id' if it is just the 'created' file like default
if (metadata.containsKey('id') && metadata.containsKey('created')) {
if (metadata['id'] == metadata['created']) {
metadata.remove('id');
}
}
str += toYAML(metadata);
str += serparator;
str += '\n';
str += note.body;
return str;
}
static String toYAML(Map<String, dynamic> map) {
var str = "";
map.forEach((key, value) {
str += key + ": " + value + "\n";
});
return str;
}
}