diff --git a/backend/src/models/Comment.js b/backend/src/models/Comment.js index e67a083..ffe0e5e 100644 --- a/backend/src/models/Comment.js +++ b/backend/src/models/Comment.js @@ -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; diff --git a/backend/tests/commentListing.test.js b/backend/tests/commentListing.test.js new file mode 100644 index 0000000..543c624 --- /dev/null +++ b/backend/tests/commentListing.test.js @@ -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']); +});