1 # This file is part of NIT ( http://www.nitlanguage.org ).
3 # This file is free software, which comes along with NIT. This software is
4 # distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
5 # without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
6 # PARTICULAR PURPOSE. You can modify it is you want, provided this header
7 # is kept unaltered, and a notification of the changes is added.
8 # You are allowed to redistribute it and sell it, alone or is a part of
11 # Store and load json data.
13 # This simple system can be used to store and retrieve json data.
17 # Create a new JsonStore or reuse an existing one.
19 # var store = new JsonStore("store_dir")
22 # JsonStore can store json of type JsonObject and JsonArray.
25 # var obj = new JsonObject
27 # obj["code"] = "FF0000"
30 # Data are stored under a key.
32 # var key = "colors/{red}"
37 # store.store_object(key, obj)
38 # assert store.has_key(key)
43 # var res = store.load_object(key)
44 # assert res["name"] == red
47 # Clear all stored data.
55 # A JsonStore can save and load json data from file system.
57 # Json files are stored under a `key`.
58 # This key represents the path to the json file from `store_dir`
59 # without the `.json` extension.
63 # * key `document` will store data under `store_dir / "document.json"`
64 # * key `collection/data` will store data under `store_dir / "collection/data.json"`
67 # Directory where data are stored.
69 # Directory is created lazilly at the first write.
72 # Delete all stored data.
74 # Warning: all `JsonStore` instances sharing the same `store_dir` will
77 if not store_dir
.file_exists
then return
81 # Is there data are stored under `key`.
82 fun has_key
(key
: String): Bool do
83 return (store_dir
/ "{key}.json").file_exists
86 # Save `json` object under `key`.
87 fun store_object
(key
: String, json
: JsonObject) do
91 # Save `json` array under `key`.
92 fun store_array
(key
: String, json
: JsonArray) do
96 # Save `json` data under `key`.
98 # Only `JsonObject` and `JsonArray` are allowed in a json file.
99 # Use `store_object` or `store_array` instead.
100 private fun store_json
(key
: String, json
: Jsonable) do
101 var path
= store_dir
/ "{key}.json"
103 var file
= new OFStream.open
(path
)
104 file
.write
(json
.to_json
)
108 # Load a JsonObject associated to `key` from store.
109 fun load_object
(key
: String): JsonObject do
110 return load_json
(key
).as(JsonObject)
113 # Load a JsonArray associated to `key` from store.
114 fun load_array
(key
: String): JsonArray do
115 return load_json
(key
).as(JsonArray)
118 # Load a JsonObject associated to `key` from store.
120 # Ensure `has_data(key)`
121 private fun load_json
(key
: String): nullable Jsonable do
123 var path
= store_dir
/ "{key}.json"
124 var file
= new IFStream.open
(path
)
125 var text
= file
.read_all
127 return text
.parse_json