Implement PostgreSQL history with user isolation

This commit is contained in:
2025-12-28 00:13:43 +11:00
parent d83a93da7e
commit 5ae3b0d036
6 changed files with 130 additions and 21 deletions

View File

@@ -81,12 +81,40 @@ async function runTest(url, options = {}) {
isMobile: isMobile
};
// Save JSON Summary
// Save JSON Summary
const jsonPath = path.join(reportDir, `${testId}.json`);
fs.writeFileSync(jsonPath, JSON.stringify(summary, null, 2));
await chrome.kill();
// Insert into Database
// We expect user_uuid and user_ip to be passed in options, or handle gracefully if not
const userUuid = options.userUuid || 'anonymous';
const userIp = options.userIp || '0.0.0.0';
const insertQuery = `
INSERT INTO test_results (id, url, timestamp, is_mobile, scores, metrics, user_uuid, user_ip)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
`;
const values = [
testId,
summary.url,
summary.timestamp,
isMobile,
summary.scores,
summary.metrics,
userUuid,
userIp
];
try {
const db = require('../lib/db');
await db.pool.query(insertQuery, values);
} catch (dbErr) {
console.error('Failed to save result to DB:', dbErr);
// Don't fail the whole test if DB save fails, just log it
}
return summary;
} catch (error) {
@@ -96,23 +124,39 @@ async function runTest(url, options = {}) {
}
/**
* Get list of all test results
* Get list of all test results (Scoped to User)
* @param {string} userUuid - User's UUID from client
* @param {string} userIp - User's IP address
*/
function getHistory() {
const reportDir = path.join(__dirname, '..', 'reports');
if (!fs.existsSync(reportDir)) return [];
async function getHistory(userUuid, userIp) {
const db = require('../lib/db');
// If no identifiers provided, return empty or limit to anonymous?
// For strict isolation, we require at least one.
if (!userUuid && !userIp) return [];
const files = fs.readdirSync(reportDir).filter(f => f.endsWith('.json'));
const history = files.map(file => {
try {
return JSON.parse(fs.readFileSync(path.join(reportDir, file), 'utf8'));
} catch (e) {
return null;
}
}).filter(Boolean);
// Sort by newest first
return history.sort((a, b) => new Date(b.timestamp) - new Date(a.timestamp));
try {
const query = `
SELECT * FROM test_results
WHERE user_uuid = $1 AND user_ip = $2
ORDER BY timestamp DESC
LIMIT 50
`;
const res = await db.pool.query(query, [userUuid, userIp]);
// Convert DB rows back to simplified history objects
return res.rows.map(row => ({
id: row.id,
url: row.url,
timestamp: row.timestamp, // JS Date
isMobile: row.is_mobile,
scores: row.scores,
metrics: row.metrics
}));
} catch (err) {
console.error('Error fetching history from DB:', err);
return [];
}
}
module.exports = {