1 # This file is part of NIT ( http://www.nitlanguage.org ).
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
7 # http://www.apache.org/licenses/LICENSE-2.0
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
15 # Enable caching on Github API accesses.
17 # If `GithubAPI::enable_cache` is set to true then Github JSON responses
18 # will be cached locally using `JsonStore`.
20 # Cache can be used to limit the number of access on the API and lighten
21 # the rate limit on your github key.
26 # var api = new GithubAPI(get_github_oauth)
27 # api.enable_cache = true
29 # var name = "nitlang/nit"
30 # assert not api.has_cache(name)
31 # var repo = api.load_repo(name) # load from GitHub
32 # #assert api.has_cache(name) FIXME bring back this assert
33 # repo = api.load_repo(name) # load from cache
36 # assert not api.has_cache(name)
40 intrude import github
::api
45 # Enable caching for this client.
47 var enable_cache
= false is writable
49 # JsonStore used to cache data.
51 # Default directory is `".github_data/"`.
52 var store
= new JsonStore(".github_data/") is writable, lazy
54 # Delete the cache directory.
55 fun clear_cache
do store
.clear
57 # If no cache data is found for `key` then json is loaded from Github API.
58 redef fun load_from_github
(key
) do
59 if not enable_cache
then return super
60 if store
.has_key
(key
) then
61 message
(1, "Get {key} (cache)")
63 return deserialize
(store
.load_object
(key
).to_json
).as(nullable GithubEntity)
67 cache
(key
, obj
.as(not null))
72 # Save `json` data in cache under `key`.
73 private fun cache
(key
: String, obj
: GithubEntity) do
74 message
(2, "Cache key {key}")
75 store
.store_object
(key
, obj
.to_json
.parse_json
.as(JsonObject))
78 # Check if a cache file exists for `key`.
79 fun has_cache
(key
: String): Bool do
80 return store
.has_key
(key
)