1 /** 2 * ae.sys.persistence.json 3 * 4 * License: 5 * This Source Code Form is subject to the terms of 6 * the Mozilla Public License, v. 2.0. If a copy of 7 * the MPL was not distributed with this file, You 8 * can obtain one at http://mozilla.org/MPL/2.0/. 9 * 10 * Authors: 11 * Vladimir Panteleev <ae@cy.md> 12 */ 13 14 module ae.sys.persistence.json; 15 16 import ae.sys.persistence.core; 17 18 // **************************************************************************** 19 20 /// `FileCache` wrapper which stores a D type as JSON serialization. 21 template JsonFileCache(T, FlushPolicy flushPolicy = FlushPolicy.none) 22 { 23 import std.file; 24 import ae.utils.json; 25 26 static T getJson(T)(string fileName) 27 { 28 return fileName.readText.jsonParse!T; 29 } 30 31 static void putJson(T)(string fileName, in T t) 32 { 33 std.file.write(fileName, t.toJson()); 34 } 35 36 alias JsonFileCache = FileCache!(getJson!T, putJson!T, flushPolicy); 37 } 38 39 unittest 40 { 41 import std.file; 42 43 enum FN = "test1.json"; 44 std.file.write(FN, "{}"); 45 scope(exit) remove(FN); 46 47 auto cache = JsonFileCache!(string[string])(FN); 48 assert(cache.length == 0); 49 } 50 51 unittest 52 { 53 import std.file; 54 55 enum FN = "test2.json"; 56 scope(exit) if (FN.exists) remove(FN); 57 58 auto cache = JsonFileCache!(string[string], FlushPolicy.manual)(FN); 59 assert(cache.length == 0); 60 cache["foo"] = "bar"; 61 cache.save(); 62 63 auto cache2 = JsonFileCache!(string[string])(FN); 64 assert(cache2["foo"] == "bar"); 65 } 66 67 unittest 68 { 69 import std.file; 70 71 enum FN = "test3.json"; 72 scope(exit) if (FN.exists) remove(FN); 73 74 { 75 auto cache = JsonFileCache!(string[string], FlushPolicy.atScopeExit)(FN); 76 cache["foo"] = "bar"; 77 } 78 79 auto cache2 = JsonFileCache!(string[string])(FN); 80 assert(cache2["foo"] == "bar"); 81 }