本文目录导读:

浏览器端(JavaScript)
/**
* 自动清理 RapiDoc 缓存脚本
* 在页面加载时清除缓存,强制重新获取 OpenAPI 文档
*/
(function() {
// 方法1:清除所有 localStorage 中的缓存数据
function clearRapiDocCache() {
const keysToRemove = [];
for (let i = 0; i < localStorage.length; i++) {
const key = localStorage.key(i);
if (key && (key.includes('rapidoc') || key.includes('rapi-doc') || key.includes('openapi'))) {
keysToRemove.push(key);
}
}
keysToRemove.forEach(key => localStorage.removeItem(key));
console.log(`已清理 ${keysToRemove.length} 个 RapiDoc 缓存项`);
}
// 方法2:清除 sessionStorage 中的缓存
function clearSessionCache() {
const keysToRemove = [];
for (let i = 0; i < sessionStorage.length; i++) {
const key = sessionStorage.key(i);
if (key && (key.includes('rapidoc') || key.includes('rapi-doc'))) {
keysToRemove.push(key);
}
}
keysToRemove.forEach(key => sessionStorage.removeItem(key));
}
// 方法3:清除 Service Worker 缓存(如果有)
async function clearServiceWorkerCache() {
if ('caches' in window) {
try {
const cacheNames = await caches.keys();
const rapicdocCaches = cacheNames.filter(name =>
name.includes('rapidoc') || name.includes('api-docs')
);
await Promise.all(
rapicdocCaches.map(cacheName => caches.delete(cacheName))
);
console.log(`已清理 ${rapicdocCaches.length} 个 Service Worker 缓存`);
} catch (error) {
console.error('清理 Service Worker 缓存失败:', error);
}
}
}
// 主执行函数
async function main() {
clearRapiDocCache();
clearSessionCache();
await clearServiceWorkerCache();
// 可选:重新加载 RapiDoc 组件
const rapidocElement = document.querySelector('rapi-doc');
if (rapidocElement) {
rapidocElement.specUrl = ''; // 清除当前 spec
setTimeout(() => {
rapidocElement.specUrl = rapidocElement.getAttribute('spec-url') || rapidocElement.specUrl;
}, 100);
}
}
// 在页面加载完成后执行
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', main);
} else {
main();
}
})();
Node.js 版本(用于前后端分离)
// cacheCleaner.js
const fs = require('fs');
const path = require('path');
const os = require('os');
class RapiDocCacheCleaner {
constructor(options = {}) {
this.cacheDir = options.cacheDir || path.join(os.tmpdir(), 'rapidoc-cache');
this.maxAge = options.maxAge || 24 * 60 * 60 * 1000; // 默认1天
}
/**
* 清理过期缓存文件
*/
cleanExpiredCache() {
if (!fs.existsSync(this.cacheDir)) {
console.log('缓存目录不存在');
return;
}
const files = fs.readdirSync(this.cacheDir);
const now = Date.now();
let cleanedCount = 0;
files.forEach(file => {
const filePath = path.join(this.cacheDir, file);
try {
const stats = fs.statSync(filePath);
const age = now - stats.mtimeMs;
if (age > this.maxAge) {
fs.unlinkSync(filePath);
cleanedCount++;
}
} catch (error) {
console.error(`清理文件失败: ${file}`, error.message);
}
});
console.log(`已清理 ${cleanedCount} 个过期缓存文件`);
}
/**
* 强制清理所有缓存
*/
cleanAllCache() {
if (!fs.existsSync(this.cacheDir)) {
return;
}
const files = fs.readdirSync(this.cacheDir);
files.forEach(file => {
const filePath = path.join(this.cacheDir, file);
try {
fs.unlinkSync(filePath);
} catch (error) {
console.error(`删除文件失败: ${file}`, error.message);
}
});
console.log('已清理所有缓存文件');
}
/**
* 定时清理任务
*/
startScheduledClean(interval = 60 * 60 * 1000) { // 默认1小时
console.log('启动定时清理任务...');
this.cleanExpiredCache();
setInterval(() => {
this.cleanExpiredCache();
}, interval);
}
}
// 使用示例
const cleaner = new RapiDocCacheCleaner({
cacheDir: './cache', // 自定义缓存目录
maxAge: 12 * 60 * 60 * 1000 // 12小时
});
cleaner.cleanAllCache(); // 强制清理
// cleaner.startScheduledClean(); // 启动定时清理
module.exports = RapiDocCacheCleaner;
使用 Service Worker 自动清理
// service-worker.js
self.addEventListener('activate', event => {
event.waitUntil(
caches.keys().then(cacheNames => {
return Promise.all(
cacheNames
.filter(name => name.includes('rapidoc') || name.includes('rapi-doc'))
.map(name => caches.delete(name))
);
}).then(() => {
console.log('RapiDoc 缓存已清理');
return self.clients.claim();
})
);
});
// 监听 fetch 事件,强制重新请求
self.addEventListener('fetch', event => {
if (event.request.url.includes('rapidoc') || event.request.url.includes('openapi')) {
event.respondWith(
fetch(event.request, {
cache: 'no-store', // 不使用缓存
headers: {
'Cache-Control': 'no-cache'
}
})
);
}
});
HTML 嵌入脚本
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">RapiDoc 自动清理缓存</title>
<script type="module" src="https://unpkg.com/rapidoc/dist/rapidoc-min.js"></script>
</head>
<body>
<rapi-doc
id="myDoc"
spec-url="https://api.example.com/openapi.json"
theme="dark"
render-style="read"
></rapi-doc>
<script>
// 在初始化前清理缓存
(async function() {
// 清理 localStorage
const cacheKeys = Object.keys(localStorage).filter(key =>
key.includes('rapidoc') || key.includes('api-doc')
);
cacheKeys.forEach(key => localStorage.removeItem(key));
// 清理 sessionStorage
const sessionKeys = Object.keys(sessionStorage).filter(key =>
key.includes('rapidoc')
);
sessionKeys.forEach(key => sessionStorage.removeItem(key));
// 清理 caches
if ('caches' in window) {
const cacheNames = await caches.keys();
await Promise.all(
cacheNames
.filter(name => name.includes('rapidoc'))
.map(name => caches.delete(name))
);
}
console.log('缓存清理完成,准备加载 RapiDoc');
})();
</script>
</body>
</html>
环境变量控制
// env-config.js
const config = {
// 开发环境:每次都清理缓存
development: {
clearCacheOnLoad: true,
cacheTTL: 0 // 立即过期
},
// 生产环境:使用合理的缓存策略
production: {
clearCacheOnLoad: false,
cacheTTL: 3600000 // 1小时
},
// 测试环境:部分清理
test: {
clearCacheOnLoad: true,
cacheTTL: 60000 // 1分钟
}
};
const env = process.env.NODE_ENV || 'development';
const currentConfig = config[env];
// 根据配置决定是否清理缓存
if (currentConfig.clearCacheOnLoad) {
// 执行清理脚本
(function clearCache() {
localStorage.clear();
sessionStorage.clear();
console.log(`[${env}] RapiDoc 缓存已清理`);
})();
}
使用方法
- 浏览器端:直接将脚本添加到 HTML 文件的
<head>中 - Node.js:在服务器启动时运行
- Service Worker:注册到你的 PWA 应用中
- 环境变量:根据开发/生产环境自动切换
注意事项
- 某些缓存可能由浏览器自动管理,无法通过 JavaScript 完全控制
- 建议在开发环境中频繁清理,生产环境中使用版本号策略
- 如果使用 CDN 版本,可能还需要清除浏览器 DNS 缓存或硬刷新 (Ctrl+F5)