Skip to content
This repository was archived by the owner on May 11, 2025. It is now read-only.

Commit 8fb9c1d

Browse files
committed
0.3
1 parent 7166357 commit 8fb9c1d

2 files changed

Lines changed: 50 additions & 9 deletions

File tree

cache.js

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
// 类似于 Service Worker 缓存机制
2+
3+
const axios = require("axios");
4+
const token = process.env.CODE_STATISTIC || "";
5+
6+
class ApiCache {
7+
constructor() {
8+
this.caches = {};
9+
}
10+
setCache(key, value, expiration) {
11+
this.caches[key] = {
12+
value: value,
13+
expiration: expiration + (new Date().getTime() / 1000),
14+
};
15+
return value;
16+
}
17+
getCache(key) {
18+
if (! key in this.caches) {
19+
return undefined;
20+
}
21+
const memory = this.caches[key];
22+
if (memory.expiration > new Date().getTime() / 1000) {
23+
return undefined;
24+
}
25+
return memory.value;
26+
}
27+
28+
async syncAxios(url) {
29+
return (await axios.get(url, {
30+
headers: {
31+
Accept: "application/json",
32+
Authorization: `Bearer ${token}`,
33+
}
34+
})).data;
35+
}
36+
37+
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;
44+
}
45+
}
46+
47+
module.exports = [
48+
token,
49+
ApiCache
50+
]

index.js

Lines changed: 0 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,7 @@
11
const express = require('express');
22
const axios = require('axios');
3-
const token = process.env.CODE_STATISTIC || "";
43
const app = express();
54

6-
async function syncAxios(url) {
7-
return (await axios.get(url, {
8-
headers: {
9-
Accept: "application/json",
10-
Authorization: `Bearer ${token}`,
11-
}
12-
})).data;
13-
}
145

156
async function getLanguage(user, repo) {
167
return await syncAxios(`https://api.github.com/repos/${user}/${repo}/languages`);

0 commit comments

Comments
 (0)