Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 11 additions & 4 deletions backend/src/models/Comment.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,19 @@ class Comment {
}

static async findByComplaintId(complaintId) {
// Keep the newest 200, shown oldest-first. Limiting the ascending list
// returned the first 200 forever, so new comments never appeared once a
// complaint passed 200. id breaks ties within the same second.
const query = `
SELECT id, complaint_id, author_name, message, created_at
FROM comments
WHERE complaint_id = $1
ORDER BY created_at ASC
LIMIT 200
FROM (
SELECT id, complaint_id, author_name, message, created_at
FROM comments
WHERE complaint_id = $1
ORDER BY created_at DESC, id DESC
LIMIT 200
) latest
ORDER BY created_at ASC, id ASC
`;
const result = await pool.query(query, [complaintId]);
return result.rows;
Expand Down
33 changes: 33 additions & 0 deletions backend/tests/commentListing.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
process.env.JWT_SECRET = process.env.JWT_SECRET || 'x'.repeat(48);
const { test, before } = require('node:test');
const assert = require('node:assert');
const initDatabase = require('../src/config/initDatabase');
const Comment = require('../src/models/Comment');

before(async () => {
await initDatabase();
});

test('a complaint with more than 200 comments lists the newest 200, oldest first', async () => {
const complaintId = `CIV-LIST-${Date.now()}`;
for (let i = 1; i <= 205; i++) {
await Comment.create({ complaintId, authorName: 'Tester', message: `comment ${i}` });
}

const comments = await Comment.findByComplaintId(complaintId);

assert.strictEqual(comments.length, 200);
assert.strictEqual(comments[0].message, 'comment 6');
assert.strictEqual(comments[199].message, 'comment 205');
});

test('comments posted in the same second keep their posting order', async () => {
const complaintId = `CIV-ORDER-${Date.now()}`;
for (const message of ['first', 'second', 'third']) {
await Comment.create({ complaintId, authorName: 'Tester', message });
}

const comments = await Comment.findByComplaintId(complaintId);

assert.deepStrictEqual(comments.map((c) => c.message), ['first', 'second', 'third']);
});
Loading