Merge: fix ci nitunit some
[nit.git] / lib / github / cache.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
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
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
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.
14
15 # Enable caching on Github API accesses.
16 #
17 # If `GithubAPI::enable_cache` is set to true then Github JSON responses
18 # will be cached locally using `JsonStore`.
19 #
20 # Cache can be used to limit the number of access on the API and lighten
21 # the rate limit on your github key.
22 #
23 # Usage:
24 #
25 # ~~~
26 # var api = new GithubAPI(get_github_oauth)
27 # api.enable_cache = true
28 #
29 # var name = "nitlang/nit"
30 # assert not api.has_cache(name)
31 # var repo = api.get_repo(name) # load from GitHub
32 # #assert api.has_cache(name) FIXME bring back this assert
33 # repo = api.get_repo(name) # load from cache
34 #
35 # api.clear_cache
36 # assert not api.has_cache(name)
37 # ~~~
38 module cache
39
40 intrude import github::api
41 import json::store
42
43 redef class GithubAPI
44
45 # Enable caching for this client.
46 # Default is `false`.
47 var enable_cache = false is writable
48
49 # JsonStore used to cache data.
50 #
51 # Default directory is `".github_data/"`.
52 var store = new JsonStore(".github_data/") is writable, lazy
53
54 # Delete the cache directory.
55 fun clear_cache do store.clear
56
57 # If no cache data is found for `key` then json is loaded from Github API.
58 redef fun get(key, headers, data) do
59 if not enable_cache then return super
60 if store.has_key(key) then
61 # print "Get {key} (cache)" # debug
62 was_error = false
63 return deserialize(store.load_object(key).to_json)
64 end
65 var obj = super
66 if not was_error and obj isa Serializable then
67 cache(key, obj)
68 end
69 return obj
70 end
71
72 # Save `json` data in cache under `key`.
73 private fun cache(key: String, obj: Serializable) do
74 # print "Cache key {key}" # debug
75 store.store_object(key, obj.to_json.parse_json.as(JsonObject))
76 end
77
78 # Check if a cache file exists for `key`.
79 fun has_cache(key: String): Bool do
80 return store.has_key(key)
81 end
82 end