Welcome to the final lesson of the course! You now have a complete ticket resource with collection queries, creation, partial updates, detail retrieval, and deletion. In this lesson, you’ll add comments as persistent child resources nested beneath individual tickets.
You’ll define the comment response model, map PostgreSQL rows into API-friendly objects, and create a dedicated child router for listing and adding comments. You’ll also see how the parent ticket router verifies that a ticket exists before allowing any nested comment request to continue.
Previously, you used router.route("/:ticketId") to group GET, PATCH, and DELETE around one ticket resource. Now that same ticket ID will identify the parent of a second resource:
text
GET /api/tickets/:ticketId/commentsPOST /api/tickets/:ticketId/comments
Understanding Nested Resources
A comment belongs to a particular ticket, so its URL is nested beneath that ticket:
text
/api/tickets/tkt_1001/comments
This path communicates the relationship directly:
text
ticket tkt_1001 └── comments
The ticket ID comes from the URL, while the comment data comes from the JSON body.
id identifies the individual comment, while ticketId links it to its parent ticket. Keeping both values in the response makes the relationship explicit to API clients.
authorId identifies the user associated with the comment. Like the earlier body-supplied requesterId, this is temporary pre-authentication scaffolding rather than a secure statement of identity.
message contains the comment text, and createdAt exposes the PostgreSQL timestamp as an ISO string. The interface uses camel-case names even though the database columns use snake case.
This unit directly supports creating and reading comments. It does not introduce comment-specific PATCH or DELETE endpoints; comments are removed automatically when their parent ticket is deleted.
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal
Representing PostgreSQL Comment Rows
The repository in src/repositories/comment-repository.ts first describes the database row shape.
Snake-case database names become camel-case API fields. Routes can therefore return TicketComment objects without knowing how PostgreSQL names its columns.
toISOString() produces a standard JSON timestamp. Reusing one mapper keeps list and creation responses consistent.
Listing a Ticket’s Comments
The repository lists comments with a parameterized parent-ticket filter.
export async function listComments( ticketId: string,): Promise<TicketComment[]> { const result = await query<CommentRow>( `SELECT id, ticket_id, author_id, message, created_at FROM ticket_comments WHERE ticket_id = $1 ORDER BY created_at ASC, id ASC`, [ticketId], ); return result.rows.map(mapCommentRow);}
WHERE ticket_id = $1 limits the result to one parent ticket. The ticket ID stays in the parameter array rather than being interpolated into SQL.
ORDER BY created_at ASC returns the conversation chronologically, with the oldest comment first. id ASC acts as a deterministic tie-breaker when timestamps are equal.
Every row passes through mapCommentRow(), so the route receives application-facing objects rather than raw database records.
An existing ticket with no comments produces an empty array. That is a valid 200 response because the collection exists even when it contains no items.
Creating a Persistent Comment
Preserving Parent Parameters with mergeParams
The comment routes live in src/routes/comment-routes.ts. The router is created with an important option:
The comment router itself defines only "/" routes. The ticketId parameter is declared by the parent mount path in ticket-routes.ts.
By default, a child Express router does not automatically receive parameters from its parent router. mergeParams: true combines those parent parameters into the child router’s request.params.
Without this option, the nested handlers would not reliably see the ticket ID from /:ticketId/comments.
The file uses a small helper to normalize the merged parameter.
Both fields must be strings containing non-whitespace content. Values such as null, arrays, and blank strings are rejected before any insert occurs.
Each error returns HTTP 400 and stops the handler immediately.
The parent ticket ID is not accepted in the body. It comes from the route, preventing the URL and body from describing different parents.
Verifying the Temporary Author
A structurally valid author ID must also reference an existing user.
const authorId = body.authorId.trim();if (!(await userExists(authorId))) { response.status(400).json({ error: { code: "INVALID_AUTHOR", message: "authorId does not reference an existing user.", }, }); return;}
userExists() performs the same parameterized user lookup introduced for ticket creation.
Returning INVALID_AUTHOR gives the client a focused response instead of exposing a PostgreSQL foreign-key failure.
This confirms referential integrity, not identity. A client can still claim another existing user’s ID until authentication replaces body-supplied authorship.
After validation, the route creates the child record.
/:ticketId/comments declares the parent parameter and identifies the nested resource branch.
The middleware calls findTicketById() before listing or creating comments. A missing parent returns 404 TICKET_NOT_FOUND.
next() is called only when the ticket exists. Express then hands the request to commentRoutes.
The child router receives ticketId because it was created with mergeParams: true.
This parent check distinguishes two valid outcomes:
Existing ticket with no comments → 200 []Missing ticket → 404 TICKET_NOT_FOUND
Without the check, both could look like an empty collection, and comment creation for a missing ticket would rely on a lower-level foreign-key error.
Why Comments Use Their Own Router
It would be possible to place every nested handler directly inside ticket-routes.ts, but that file already owns collection filtering, creation, statistics, retrieval, updates, and deletion.
A dedicated commentRoutes module:
Keeps comment validation and handlers together.
Allows the repository flow to evolve without bloating the parent router.
Makes the ticket router responsible only for mounting the child and verifying the parent.
Preserves the resource relationship through the nested URL.
This pattern can later support other ticket child resources without turning one router into an oversized file.
Deleting the Parent and Its Comments
There is no direct comment deletion endpoint in this unit. Instead, PostgreSQL removes child comments when their parent ticket is deleted because the foreign key is configured with ON DELETE CASCADE.
A successful request returns 201 with the newly stored comment. Send the GET request again and confirm that the new comment now appears in the collection.
Try an invalid author:
{ "authorId": "usr_missing", "message": "This should not be inserted."}
The API should return 400 INVALID_AUTHOR.
Try a blank message:
{ "authorId": "usr_agent_1", "message": " "}
The API should return 400 INVALID_BODY.
Finally, request comments for a nonexistent parent:
GET /api/tickets/tkt_missing/comments
The ticket middleware should return 404 TICKET_NOT_FOUND before the comment repository runs.
Completing a Disposable Resource Lifecycle
A useful final checkpoint is to exercise the full parent-child lifecycle without modifying seeded tickets.
Create a ticket:
POST /api/tickets
{ "title": "Disposable nested-route ticket", "description": "Used to verify comment persistence and cascade deletion.", "priority": "medium", "requesterId": "usr_customer_1"}
Copy the returned ticket ID and add a comment:
POST /api/tickets/<new-id>/comments
{ "authorId": "usr_customer_1", "message": "First comment on the disposable ticket."}
Then verify the complete sequence:
GET /api/tickets/<new-id>/commentsPATCH /api/tickets/<new-id>DELETE /api/tickets/<new-id>GET /api/tickets/<new-id>GET /api/tickets/<new-id>/comments
The delete should return 204, and both later GET requests should return 404.
Recap
You’ve completed the course with a persistent nested child resource. TicketComment defines the public shape, comment-repository.ts handles parameterized reads and inserts, and comment-routes.ts validates comment requests without bloating the ticket router.
The key routing feature is Router({ mergeParams: true }), which allows the child router to receive the ticketId declared by its parent mount. Before that router runs, parent-existence middleware distinguishes an empty comment collection from a missing ticket.
Together, the API now supports filtered ticket collections, ticket creation, detail retrieval, partial updates, deletion, comment listing, comment creation, and cascading child cleanup through PostgreSQL.
export async function listComments( ticketId: string,): Promise<TicketComment[]> { const result = await query<CommentRow>( `SELECT id, ticket_id, author_id, message, created_at FROM ticket_comments WHERE ticket_id = $1 ORDER BY created_at ASC, id ASC`, [ticketId], ); return result.rows.map(mapCommentRow);}
The mutation repository function creates a server-owned comment ID and asks PostgreSQL to return the stored row.