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 <vladimir@thecybershadow.net>
12  */
13 
14 module ae.sys.persistence.json;
15 
16 import ae.sys.persistence.core;
17 
18 // ****************************************************************************
19 
20 template JsonFileCache(T, FlushPolicy flushPolicy = FlushPolicy.none)
21 {
22 	import std.file;
23 	import ae.utils.json;
24 
25 	static T getJson(T)(string fileName)
26 	{
27 		return fileName.readText.jsonParse!T;
28 	}
29 
30 	static void putJson(T)(string fileName, in T t)
31 	{
32 		std.file.write(fileName, t.toJson());
33 	}
34 
35 	alias JsonFileCache = FileCache!(getJson!T, putJson!T, flushPolicy);
36 }
37 
38 unittest
39 {
40 	import std.file;
41 
42 	enum FN = "test1.json";
43 	std.file.write(FN, "{}");
44 	scope(exit) remove(FN);
45 
46 	auto cache = JsonFileCache!(string[string])(FN);
47 	assert(cache.length == 0);
48 }
49 
50 unittest
51 {
52 	import std.file;
53 
54 	enum FN = "test2.json";
55 	scope(exit) if (FN.exists) remove(FN);
56 
57 	auto cache = JsonFileCache!(string[string], FlushPolicy.manual)(FN);
58 	assert(cache.length == 0);
59 	cache["foo"] = "bar";
60 	cache.save();
61 
62 	auto cache2 = JsonFileCache!(string[string])(FN);
63 	assert(cache2["foo"] == "bar");
64 }
65 
66 unittest
67 {
68 	import std.file;
69 
70 	enum FN = "test3.json";
71 	scope(exit) if (FN.exists) remove(FN);
72 
73 	{
74 		auto cache = JsonFileCache!(string[string], FlushPolicy.atScopeExit)(FN);
75 		cache["foo"] = "bar";
76 	}
77 
78 	auto cache2 = JsonFileCache!(string[string])(FN);
79 	assert(cache2["foo"] == "bar");
80 }