Files
baby-tracker/test_api.js
T
2026-09-25 22:08:37 +08:00

265 lines
9.2 KiB
JavaScript

const http = require('http');
const PORT = process.env.PORT || 9898;
function request(options, data = null) {
return new Promise((resolve, reject) => {
const req = http.request({ port: PORT, ...options }, (res) => {
let body = '';
res.on('data', chunk => body += chunk);
res.on('end', () => {
try {
resolve({ status: res.statusCode, data: JSON.parse(body) });
} catch (e) {
resolve({ status: res.statusCode, text: body });
}
});
});
req.on('error', reject);
if (data) {
req.write(typeof data === 'string' ? data : JSON.stringify(data));
}
req.end();
});
}
async function runTests() {
console.log('--- Starting API End-to-End Verification ---');
// 1. Get Babies
const babiesRes = await request({
hostname: 'localhost',
path: '/api/babies',
method: 'GET'
});
console.log('1. GET /api/babies:', babiesRes.status, 'Babies found:', babiesRes.data.data.length);
const baby = babiesRes.data.data[0];
console.log(' Active baby:', baby.name, 'ID:', baby.baby_id, 'Age:', baby.ageText);
// 2. Test Baby Update (PUT /api/babies/:babyId)
const updateRes = await request({
hostname: 'localhost',
path: `/api/babies/${baby.baby_id}`,
method: 'PUT',
headers: { 'Content-Type': 'application/json' }
}, {
name: baby.name,
gender: baby.gender,
birthDate: baby.birth_date,
themeColor: baby.theme_color
});
console.log('2. PUT /api/babies/:babyId:', updateRes.status, 'Success:', updateRes.data.success);
// 3. Test Custom Metric Creation & Query & Cleanup
const customRes = await request({
hostname: 'localhost',
path: '/api/custom-metrics',
method: 'POST',
headers: { 'Content-Type': 'application/json' }
}, {
babyId: baby.baby_id,
name: '临时测试指标',
icon: '💊',
unit: '滴',
dailyTarget: 1,
type: 'count'
});
console.log('3. POST /api/custom-metrics:', customRes.status, 'Success:', customRes.data.success);
const testMetricId = customRes.data.data?.metric_id;
const listCustomRes = await request({
hostname: 'localhost',
path: `/api/custom-metrics?babyId=${baby.baby_id}`,
method: 'GET'
});
console.log(' GET /api/custom-metrics:', listCustomRes.status, 'Metrics count:', listCustomRes.data.data.length);
if (testMetricId) {
await request({
hostname: 'localhost',
path: `/api/custom-metrics/${testMetricId}`,
method: 'DELETE'
});
}
// 4. Test Quick Logging: Bottle Record
const bottleRes = await request({
hostname: 'localhost',
path: '/api/records',
method: 'POST',
headers: { 'Content-Type': 'application/json' }
}, {
babyId: baby.baby_id,
operatorName: '宝妈',
activityType: 'bottle',
durationMinutes: 15,
payload: { amountMl: 120, milkType: 'formula', note: '测试120ml配方奶' }
});
console.log('4. POST /api/records (bottle 120ml):', bottleRes.status, 'Success:', bottleRes.data.success);
// 5. Test Quick Logging: Custom Metric
const customLogRes = await request({
hostname: 'localhost',
path: '/api/records',
method: 'POST',
headers: { 'Content-Type': 'application/json' }
}, {
babyId: baby.baby_id,
operatorName: '宝爸',
activityType: 'custom',
durationMinutes: 1,
payload: { name: '补充维D3滴剂', icon: '💊', unit: '滴', value: 1, note: '餐后按时服用' }
});
console.log('5. POST /api/records (custom goal):', customLogRes.status, 'Success:', customLogRes.data.success);
// 6. Test Summary (KPI, 4-Period Slots, Custom Goals)
const summaryRes = await request({
hostname: 'localhost',
path: `/api/summary?babyId=${baby.baby_id}`,
method: 'GET'
});
console.log('6. GET /api/summary:', summaryRes.status, 'Success:', summaryRes.data.success);
const s = summaryRes.data.data;
console.log(' KPI Total Milk:', s.kpi.feeding.totalBottleMl, 'ml');
console.log(' KPI Total Sleep:', s.kpi.sleep.totalSleepText);
console.log(' KPI Diaper:', s.kpi.diaper.diaperCount, 'times');
console.log(' Period Slots available:', Object.keys(s.periodSlots));
console.log(' Period Dawn items:', s.periodSlots.dawn.items.length);
console.log(' Period Morning items:', s.periodSlots.morning.items.length);
console.log(' Period Afternoon items:', s.periodSlots.afternoon.items.length);
console.log(' Period Evening items:', s.periodSlots.evening.items.length);
// 7. Test Care Guides
const guidesRes = await request({
hostname: 'localhost',
path: '/api/care-guides',
method: 'GET'
});
console.log('7. GET /api/care-guides:', guidesRes.status, 'Guides count:', guidesRes.data.data.length);
// 8. Test Family Memos CRUD
console.log('\n--- Testing Family Memos CRUD ---');
const familiesRes = await request({ hostname: 'localhost', path: '/api/families', method: 'GET' });
const testFamilyId = familiesRes.data.data[0].family_id;
// 8a. Create Memo
const createMemoRes = await request({
hostname: 'localhost',
path: '/api/memos',
method: 'POST',
headers: { 'Content-Type': 'application/json' }
}, {
familyId: testFamilyId,
babyId: baby.baby_id,
content: '测试备忘待办:下午3点测温并做抚触操',
duePeriod: 'afternoon',
creatorRole: '宝妈'
});
console.log('8a. POST /api/memos:', createMemoRes.status, 'Memo ID:', createMemoRes.data.data?.memo_id);
const memoId = createMemoRes.data.data?.memo_id;
// 8b. Get Memos
const getMemosRes = await request({
hostname: 'localhost',
path: `/api/memos?familyId=${testFamilyId}`,
method: 'GET'
});
console.log('8b. GET /api/memos:', getMemosRes.status, 'Memos count:', getMemosRes.data.data?.length);
// 8c. Update Memo (mark completed & edit content)
const updateMemoRes = await request({
hostname: 'localhost',
path: `/api/memos/${memoId}`,
method: 'PUT',
headers: { 'Content-Type': 'application/json' }
}, {
content: '测试备忘待办:下午3点测温(已复测正常)',
isCompleted: true,
duePeriod: 'afternoon'
});
console.log('8c. PUT /api/memos/:id (update content & complete):', updateMemoRes.status, 'Success:', updateMemoRes.data.success);
// 8d. Query Historical Memos with Filters (status & search)
const filterMemosRes = await request({
hostname: 'localhost',
path: `/api/memos?familyId=${testFamilyId}&status=completed&search=${encodeURIComponent('测温')}`,
method: 'GET'
});
console.log('8d. GET /api/memos (filter status=completed & search=测温):', filterMemosRes.status, 'Filtered count:', filterMemosRes.data.data?.length);
// 8e. Clear Completed Memos
const clearMemosRes = await request({
hostname: 'localhost',
path: '/api/memos/clear-completed',
method: 'POST',
headers: { 'Content-Type': 'application/json' }
}, {
familyId: testFamilyId
});
console.log('8e. POST /api/memos/clear-completed:', clearMemosRes.status, 'Cleared count:', clearMemosRes.data.affectedRows);
// 9. Test Role Preferences Persistence
console.log('\n--- Testing Role Preferences ---');
const rolePrefRes = await request({
hostname: 'localhost',
path: `/api/families/${testFamilyId}/members/${encodeURIComponent('宝爸')}/preferences`,
method: 'PUT',
headers: { 'Content-Type': 'application/json' }
}, {
preferences: {
defaultFeedingMode: 'bottle',
defaultBottleMl: 150,
defaultBfMinutes: 15
}
});
console.log('9. PUT /api/families/:id/members/:role/preferences:', rolePrefRes.status, 'Success:', rolePrefRes.data.success);
// 10. Test Baby Default Config
console.log('\n--- Testing Baby Default Config ---');
const defaultsRes = await request({
hostname: 'localhost',
path: `/api/babies/${baby.baby_id}/defaults`,
method: 'PUT',
headers: { 'Content-Type': 'application/json' }
}, {
defaultConfig: {
feedingMode: 'breastfeed',
bottleAmountMl: 120,
bfDurationMinutes: 20
}
});
console.log('10. PUT /api/babies/:id/defaults:', defaultsRes.status, 'Success:', defaultsRes.data.success);
// 11. Test Breastfeed Record with Start & End Time + Duration
console.log('\n--- Testing Breastfeed Record with Duration ---');
const now = new Date();
const startTime = new Date(now.getTime() - 25 * 60000);
const pad = n => String(n).padStart(2, '0');
const fmt = d => `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
const bfRecordRes = await request({
hostname: 'localhost',
path: '/api/records',
method: 'POST',
headers: { 'Content-Type': 'application/json' }
}, {
babyId: baby.baby_id,
operatorName: '宝妈',
activityType: 'breastfeed',
startTime: fmt(startTime),
endTime: fmt(now),
durationMinutes: 25,
payload: {
leftMinutes: 13,
rightMinutes: 12,
note: '亲喂倒计时专注打卡测试'
}
});
console.log('11. POST /api/records (breastfeed 25min):', bfRecordRes.status, 'Success:', bfRecordRes.data.success);
console.log('\n=============================================');
console.log('🎉 All 11 API End-to-End Tests Passed Successfully!');
console.log('=============================================');
}
runTests().catch(console.error);