更新 worker.js
This commit is contained in:
58
worker.js
58
worker.js
@@ -70,6 +70,12 @@ addEventListener('fetch', (event) => {
|
||||
break;
|
||||
case '/load-notification':
|
||||
return loadNotification();
|
||||
case '/export':
|
||||
return exportData(); // 导出接口
|
||||
|
||||
case '/import':
|
||||
if (request.method === 'POST') return importData(request);
|
||||
break;
|
||||
}
|
||||
|
||||
// 未匹配的路由返回404
|
||||
@@ -94,6 +100,58 @@ addEventListener('fetch', (event) => {
|
||||
|
||||
return parsedData;
|
||||
}
|
||||
// 导出导航数据为 JSON 文件
|
||||
async function exportData() {
|
||||
const navigationData = await getNavigationData(); // 复用已有函数
|
||||
const jsonStr = JSON.stringify(navigationData, null, 2);
|
||||
|
||||
return new Response(jsonStr, {
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Content-Disposition': 'attachment; filename="navigation_backup.json"',
|
||||
},
|
||||
});
|
||||
}
|
||||
// 从上传的 JSON 文件导入导航数据
|
||||
async function importData(request) {
|
||||
try {
|
||||
const formData = await request.formData();
|
||||
const file = formData.get('file');
|
||||
|
||||
if (!file) {
|
||||
return new Response(JSON.stringify({ error: '请选择要导入的文件' }), {
|
||||
status: 400,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
});
|
||||
}
|
||||
|
||||
// 读取文件内容
|
||||
const fileText = await file.text();
|
||||
const importedData = JSON.parse(fileText);
|
||||
|
||||
// 简单验证格式:必须包含 categories 数组
|
||||
if (!importedData || !Array.isArray(importedData.categories)) {
|
||||
return new Response(JSON.stringify({ error: '无效的备份文件格式,缺少 categories 数组' }), {
|
||||
status: 400,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
});
|
||||
}
|
||||
|
||||
// 可选:进一步验证每个分类和站点结构(这里略,可根据需要补充)
|
||||
|
||||
// 写入 KV
|
||||
await NAVIGATION_DATA.put('data', JSON.stringify(importedData));
|
||||
|
||||
return new Response(JSON.stringify({ message: '数据导入成功' }), {
|
||||
headers: { 'Content-Type': 'application/json; charset=utf-8' },
|
||||
});
|
||||
} catch (error) {
|
||||
return new Response(JSON.stringify({ error: '导入失败:' + error.message }), {
|
||||
status: 500,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
});
|
||||
}
|
||||
}
|
||||
// 添加站点重新排序功能
|
||||
async function reorderSite(request) {
|
||||
const requestBody = await request.json();
|
||||
|
||||
Reference in New Issue
Block a user