1- // 类似于 Service Worker 缓存机制
2-
1+ const logger = ( require ( "log4js" ) ) . getLogger ( "Cache" ) ;
32const axios = require ( "axios" ) ;
4- const token = process . env . CODE_STATISTIC || "" ;
53
6- class ApiCache {
4+ logger . level = "debug" ;
5+ axios . defaults . baseURL = "https://api.github.com" ;
6+
7+ class LightCache {
78 constructor ( ) {
89 this . caches = { } ;
910 }
@@ -15,7 +16,7 @@ class ApiCache {
1516 return value ;
1617 }
1718 getCache ( key ) {
18- if ( ! key in this . caches ) {
19+ if ( ! ( key in this . caches ) ) {
1920 return undefined ;
2021 }
2122 const memory = this . caches [ key ] ;
@@ -24,27 +25,42 @@ class ApiCache {
2425 }
2526 return memory . value ;
2627 }
27-
28+ getOrSet ( key , sync , expiration ) {
29+ const cache = this . getCache ( key ) ;
30+ return cache === undefined ? this . setCache ( key , sync ( ) , expiration ) : cache ;
31+ }
32+ async asyncGetOrSet ( key , async , expiration ) {
33+ const cache = this . getCache ( key ) ;
34+ return cache === undefined ? this . setCache ( key , await async ( ) , expiration ) : cache ;
35+ }
36+ }
37+
38+ class ApiCache extends LightCache {
39+ constructor ( token ) {
40+ super ( ) ;
41+ this . token = token ;
42+ }
2843 async syncAxios ( url ) {
44+ logger . debug ( "Request GitHub API address:" , url ) ;
2945 return ( await axios . get ( url , {
3046 headers : {
3147 Accept : "application/json" ,
32- Authorization : `Bearer ${ token } ` ,
48+ Authorization : `Bearer ${ this . token } ` ,
3349 }
3450 } ) ) . data ;
3551 }
3652
3753 async requestWithCache ( url , expiration = 3600 ) {
38- const cache = this . getCache ( url ) ;
39- if ( ! cache === undefined ) {
40- const resp = await this . syncAxios ( url ) ;
41- return this . setCache ( url , resp , expiration ) ;
42- }
43- return cache ;
54+ // 类似于 Service Worker 缓存机制
55+ return this . asyncGetOrSet (
56+ url ,
57+ async ( ) => ( await this . syncAxios ( url ) ) ,
58+ expiration ,
59+ ) ;
4460 }
4561}
4662
47- module . exports = [
48- token ,
49- ApiCache
50- ]
63+ module . exports = {
64+ LightCache : LightCache ,
65+ ApiCache : ApiCache ,
66+ }
0 commit comments