Files
nxxmdata/backend/examples/api-client-example.js

273 lines
5.9 KiB
JavaScript
Raw Normal View History

/**
* 前端API调用示例
* 展示如何使用fetch方法与后端API进行交互
*/
const API_BASE_URL = 'http://localhost:3000/api';
/**
* 统一的API请求函数
* @param {string} endpoint - API端点
* @param {Object} options - 请求选项
* @returns {Promise} API响应
*/
async function apiRequest(endpoint, options = {}) {
const url = `${API_BASE_URL}${endpoint}`;
const defaultOptions = {
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
},
credentials: 'include',
};
const config = {
...defaultOptions,
...options,
headers: {
...defaultOptions.headers,
...options.headers,
},
};
try {
const response = await fetch(url, config);
// 检查响应状态
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const result = await response.json();
// 检查API响应状态
if (result.status === 'error') {
throw new Error(result.message || 'API请求失败');
}
return result;
} catch (error) {
console.error('API请求失败:', error);
throw error;
}
}
/**
* 获取动物列表
* @param {Object} filters - 筛选条件
* @param {number} page - 页码
* @param {number} limit - 每页数量
* @returns {Promise} 动物列表数据
*/
async function fetchAnimals(filters = {}, page = 1, limit = 20) {
// 构建查询参数
const params = new URLSearchParams({
page: page.toString(),
limit: limit.toString(),
...filters
});
// 移除空值参数
Array.from(params.keys()).forEach(key => {
if (!params.get(key)) {
params.delete(key);
}
});
return apiRequest(`/demo/animals?${params.toString()}`);
}
/**
* 获取设备列表
* @param {Object} filters - 筛选条件
* @param {number} page - 页码
* @param {number} limit - 每页数量
* @returns {Promise} 设备列表数据
*/
async function fetchDevices(filters = {}, page = 1, limit = 20) {
const params = new URLSearchParams({
page: page.toString(),
limit: limit.toString(),
...filters
});
// 移除空值参数
Array.from(params.keys()).forEach(key => {
if (!params.get(key)) {
params.delete(key);
}
});
return apiRequest(`/demo/devices?${params.toString()}`);
}
/**
* 获取告警列表
* @param {Object} filters - 筛选条件
* @param {number} page - 页码
* @param {number} limit - 每页数量
* @returns {Promise} 告警列表数据
*/
async function fetchAlerts(filters = {}, page = 1, limit = 20) {
const params = new URLSearchParams({
page: page.toString(),
limit: limit.toString(),
...filters
});
// 移除空值参数
Array.from(params.keys()).forEach(key => {
if (!params.get(key)) {
params.delete(key);
}
});
return apiRequest(`/demo/alerts?${params.toString()}`);
}
/**
* 获取仪表盘数据
* @returns {Promise} 仪表盘数据
*/
async function fetchDashboard() {
return apiRequest('/demo/dashboard');
}
/**
* 创建新的动物
* @param {Object} animalData - 动物数据
* @returns {Promise} 创建结果
*/
async function createAnimal(animalData) {
return apiRequest('/demo/animals', {
method: 'POST',
body: JSON.stringify(animalData)
});
}
/**
* 更新动物信息
* @param {number} id - 动物ID
* @param {Object} updates - 更新数据
* @returns {Promise} 更新结果
*/
async function updateAnimal(id, updates) {
return apiRequest(`/demo/animals/${id}`, {
method: 'PUT',
body: JSON.stringify(updates)
});
}
/**
* 删除动物
* @param {number} id - 动物ID
* @returns {Promise} 删除结果
*/
async function deleteAnimal(id) {
return apiRequest(`/demo/animals/${id}`, {
method: 'DELETE'
});
}
/**
* 处理告警
* @param {number} id - 告警ID
* @param {Object} handleData - 处理数据
* @returns {Promise} 处理结果
*/
async function handleAlert(id, handleData) {
return apiRequest(`/demo/alerts/${id}/handle`, {
method: 'POST',
body: JSON.stringify(handleData)
});
}
// 使用示例
async function demo() {
console.log('=== API调用演示 ===');
try {
// 1. 获取仪表盘数据
console.log('1. 获取仪表盘数据...');
const dashboard = await fetchDashboard();
console.log('仪表盘数据:', dashboard.data);
// 2. 获取动物列表(带筛选条件)
console.log('\n2. 获取动物列表...');
const animals = await fetchAnimals({
category: 'cattle',
status: 'active',
minWeight: '200',
maxWeight: '500'
}, 1, 10);
console.log('动物列表:', animals.data);
console.log('总数:', animals.total);
// 3. 获取设备列表
console.log('\n3. 获取设备列表...');
const devices = await fetchDevices({
type: 'sensor',
status: 'online'
}, 1, 5);
console.log('设备列表:', devices.data);
// 4. 获取告警列表
console.log('\n4. 获取告警列表...');
const alerts = await fetchAlerts({
level: 'high',
status: 'pending'
}, 1, 5);
console.log('告警列表:', alerts.data);
} catch (error) {
console.error('演示失败:', error.message);
}
}
// Vue 3 Composition API 使用示例
const apiExample = {
// 动物管理相关API
animals: {
fetch: fetchAnimals,
create: createAnimal,
update: updateAnimal,
delete: deleteAnimal
},
// 设备管理相关API
devices: {
fetch: fetchDevices
},
// 告警管理相关API
alerts: {
fetch: fetchAlerts,
handle: handleAlert
},
// 统计相关API
stats: {
dashboard: fetchDashboard
}
};
// 导出API方法
module.exports = {
apiRequest,
fetchAnimals,
fetchDevices,
fetchAlerts,
fetchDashboard,
createAnimal,
updateAnimal,
deleteAnimal,
handleAlert,
demo
};
// 如果直接运行此文件,执行演示
if (require.main === module) {
demo();
}