Skip to content

Commit 28e5c8f

Browse files
committed
Fix activity pagination: safer SQL, better error logging, parameter validation
1 parent 93d237c commit 28e5c8f

2 files changed

Lines changed: 9 additions & 8 deletions

File tree

server.js

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -104,21 +104,21 @@ app.get('/api/activity', async (req, res) => {
104104
const decoded = jwt.verify(token, process.env.JWT_SECRET);
105105
const userId = decoded.userId;
106106

107-
const limit = Math.min(parseInt(req.query.limit) || 20, 50);
108-
const offset = parseInt(req.query.offset) || 0;
107+
const limit = Math.max(1, Math.min(parseInt(req.query.limit) || 20, 50));
108+
const offset = Math.max(0, parseInt(req.query.offset) || 0);
109109
const result = await getRecentActivity(userId, limit, offset);
110110
res.json({
111111
activities: result.activities,
112112
total: result.total,
113113
page: Math.floor(offset / limit) + 1,
114-
totalPages: Math.ceil(result.total / limit),
114+
totalPages: Math.ceil(result.total / limit) || 1,
115115
limit,
116116
});
117117
} catch (err) {
118118
if (err.name === 'JsonWebTokenError' || err.name === 'TokenExpiredError') {
119119
return res.status(401).json({ error: 'Invalid or expired token' });
120120
}
121-
console.error('Activity route error:', err.message);
121+
console.error('Activity route error:', err.message, err.stack?.split('\n')[1]);
122122
res.status(500).json({ error: 'Failed to fetch activities' });
123123
}
124124
});

services/activity.js

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -12,13 +12,14 @@ export async function logActivity(userId, action, details = '', serverId = null)
1212
}
1313

1414
export async function getRecentActivity(userId, limit = 20, offset = 0) {
15-
const [countResult] = await query(
15+
const countRows = await query(
1616
'SELECT COUNT(*) as total FROM activity_log WHERE user_id = ?',
1717
[userId]
1818
);
19+
const total = (countRows && countRows[0]) ? countRows[0].total : 0;
1920
const rows = await query(
20-
'SELECT * FROM activity_log WHERE user_id = ? ORDER BY created_at DESC LIMIT ? OFFSET ?',
21-
[userId, limit, offset]
21+
'SELECT * FROM activity_log WHERE user_id = ? ORDER BY created_at DESC LIMIT ?, ?',
22+
[userId, offset, limit]
2223
);
23-
return { activities: rows, total: countResult.total };
24+
return { activities: rows, total };
2425
}

0 commit comments

Comments
 (0)