Files
dns-server/static/js/api.js
2025-11-25 01:34:20 +08:00

100 lines
2.6 KiB
JavaScript

// API模块 - 统一管理所有API调用
// API路径定义
const API_BASE_URL = '/api';
// API请求封装
async function apiRequest(endpoint, method = 'GET', data = null) {
const url = `${API_BASE_URL}${endpoint}`;
const options = {
method,
headers: {
'Content-Type': 'application/json',
},
};
if (data) {
options.body = JSON.stringify(data);
}
try {
const response = await fetch(url, options);
if (!response.ok) {
const errorData = await response.json().catch(() => ({}));
throw new Error(errorData.error || `请求失败: ${response.status}`);
}
return await response.json();
} catch (error) {
console.error('API请求错误:', error);
throw error;
}
}
// API方法集合
// API方法集合
const api = {
// 获取统计信息
getStats: () => apiRequest('/stats'),
// 获取系统状态
getStatus: () => apiRequest('/status'),
// 获取Top屏蔽域名
getTopBlockedDomains: () => apiRequest('/top-blocked'),
// 获取Top解析域名
getTopResolvedDomains: () => apiRequest('/top-resolved'),
// 获取最近屏蔽域名
getRecentBlockedDomains: () => apiRequest('/recent-blocked'),
// 获取小时统计
getHourlyStats: () => apiRequest('/hourly-stats'),
// 获取屏蔽规则
getShieldRules: () => apiRequest('/shield'),
// 添加屏蔽规则
addShieldRule: (rule) => apiRequest('/shield', 'POST', { rule }),
// 删除屏蔽规则
deleteShieldRule: (rule) => apiRequest('/shield', 'DELETE', { rule }),
// 更新远程规则
updateRemoteRules: () => apiRequest('/shield', 'PUT', { action: 'update' }),
// 获取黑名单列表
getBlacklists: () => apiRequest('/shield/blacklists'),
// 添加黑名单
addBlacklist: (url) => apiRequest('/shield/blacklists', 'POST', { url }),
// 删除黑名单
deleteBlacklist: (url) => apiRequest('/shield/blacklists', 'DELETE', { url }),
// 获取Hosts内容
getHosts: () => apiRequest('/shield/hosts'),
// 保存Hosts内容
saveHosts: (content) => apiRequest('/shield/hosts', 'POST', { content }),
// 刷新Hosts
refreshHosts: () => apiRequest('/shield/hosts', 'PUT', { action: 'refresh' }),
// 执行DNS查询
queryDNS: (domain, recordType = 'A') => apiRequest(`/query?domain=${encodeURIComponent(domain)}&type=${recordType}`),
// 获取系统配置
getConfig: () => apiRequest('/config'),
// 保存系统配置
saveConfig: (config) => apiRequest('/config', 'POST', config),
// 重启服务
restartService: () => apiRequest('/config/restart', 'POST'),
};
// 导出API工具
window.api = api;