1 /**
2   A simple JSON storage wrapper.
3 */
4 module dcord.util.storage;
5 
6 import std.file : read, write, exists;
7 import std.path : dirSeparator;
8 import dcord.util.json;
9 
10 class Storage {
11   VibeJSON  obj;
12   string    path;
13 
14   this(string path) {
15     this.path = path;
16   }
17 
18   void load() {
19     if (exists(this.path)) {
20       this.obj = parseJsonString(cast(string)read(this.path));
21     } else {
22       this.obj = VibeJSON.emptyObject;
23     }
24   }
25 
26   void save() {
27     write(this.path, this.obj.toPrettyString());
28   }
29 
30   VibeJSON ensureObject(string key) {
31     if (!this.has(key)) {
32       this.obj[key] = VibeJSON.emptyObject;
33     }
34 
35     return this.obj[key];
36   }
37 
38   void set(string key, VibeJSON o) {
39     this.obj[key] = o;
40   }
41 
42   VibeJSON opIndex(string key) {
43     return this.obj[key];
44   }
45 
46   bool has(string key) {
47     return !((key in this.obj) is null);
48   }
49 
50   T get(T)(string key) {
51     return this.obj[key].get!T;
52   }
53 
54   T get(T)(string key, T def) {
55     if (this.has(key)) {
56       return this.get!T(key);
57     }
58     return def;
59   }
60 }