增加数据访问统计

This commit is contained in:
2024-10-14 17:13:29 +08:00
parent ef878eade1
commit 9b88bedb80
3 changed files with 45 additions and 48 deletions

View File

@@ -11,6 +11,17 @@ const cacheDir = pathModule.join(__dirname, '.cache');
const args = process.argv.slice(2);
const pathIndex = {};
// 增加访问计数器
const viewsInfo = {
// 请求次数
request: 0,
// 缓存命中次数
cacheHit: 0,
// API调用次数
apiCall: 0,
};
// 默认端口号和 API 地址
let port = 9001;
let apiEndpoint = 'https://oss.x-php.com/alist/link';
@@ -41,14 +52,13 @@ setInterval(() => {
delete pathIndex[key];
}
}
}, 60 * 60 * 1000); // 每隔 1 小时执行一次
}, 60 * 60 * 1000); // 每隔 1 小时执行一次
// 处理请求并返回数据
const server = http.createServer(async (req, res) => {
req.url = req.url.replace(/\/{2,}/g, '/');
if (req.url === '/favicon.ico') {
res.writeHead(204);
res.end();
@@ -65,6 +75,7 @@ const server = http.createServer(async (req, res) => {
port: port,
cacheDir: cacheDir,
pathIndexCount: Object.keys(pathIndex).length,
viewsInfo: viewsInfo
}
}));
return;
@@ -80,6 +91,9 @@ const server = http.createServer(async (req, res) => {
return;
}
// 增加请求次数
viewsInfo.request++;
const uniqidhex = crypto.createHash('md5').update(reqPath + sign).digest('hex');
let cacheMetaFile = '';
@@ -92,9 +106,17 @@ const server = http.createServer(async (req, res) => {
}
if (pathIndex[uniqidhex] && isCacheValid(cacheMetaFile, cacheContentFile)) {
// 增加缓存命中次数
viewsInfo.cacheHit++;
serveFromCache(cacheMetaFile, cacheContentFile, res);
} else {
try {
// 增加 API 调用次数
viewsInfo.apiCall++;
const apiData = await fetchApiData(reqPath, sign);
if (apiData.code === 200 && apiData.data && apiData.data.url) {
const { url: realUrl, cloudtype, expiration, path, headers, uniqid } = apiData.data;