Last active
March 25, 2021 18:43
-
-
Save lukepighetti/ee0eeb4b64e395da074d499c6900ffb7 to your computer and use it in GitHub Desktop.
A dead simple JSON based key/value store that is unbelievably useful for scripts and tools
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'dart:convert'; | |
import 'dart:io'; | |
class Database { | |
/// A simple JSON file database | |
Database(String path) : file = File(path); | |
final File file; | |
var _store = <String, dynamic>{}; | |
/// Fetch the file database and hold it in memory. | |
Future<void> initState() async { | |
try { | |
final string = await file.readAsString(); | |
_store = jsonDecode(string); | |
} on FileSystemException catch (e) { | |
switch (e.osError.errorCode) { | |
/// No such file or directory | |
case 2: | |
await file.create(recursive: true); | |
break; | |
default: | |
rethrow; | |
} | |
} on FormatException catch (_) { | |
await file.writeAsString('{}'); | |
} | |
} | |
/// Read a key from the database | |
Future<dynamic> read(String key) async { | |
return _store[key]; | |
} | |
/// Set a key in the database. Inserts/updates automatically. | |
Future<void> upsert(String key, dynamic value) async { | |
_store[key] = value; | |
await _updateFileFromStore(); | |
} | |
/// Delete a key in the database. | |
Future<void> delete(String key, dynamic value) async { | |
_store.remove(key); | |
await _updateFileFromStore(); | |
} | |
Future<void> _updateFileFromStore() async { | |
final encoder = JsonEncoder.withIndent(' '); | |
final prettyprint = encoder.convert(_store); | |
await file.writeAsString(prettyprint); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'database.dart'; | |
void main() async { | |
/// Setup database | |
final db = Database('example_database.json'); | |
await db.initState(); | |
/// Add an entry | |
await db.upsert('key', 'value'); | |
/// Returns `value` | |
print(await db.read('key')); | |
/// Delete the entry | |
await db.delete('key', 'value'); | |
/// Returns `null` | |
print(await db.read('key')); | |
/// Save an entry for posterity | |
await db.upsert('graffiti', 'you wuz here ${DateTime.now().year}'); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"graffiti": "you wuz here 2021" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment