Skip to content

Refactor handheld comment creation#439

Merged
Producdevity merged 2 commits into
stagingfrom
refactor/comment-create-service
Jun 6, 2026
Merged

Refactor handheld comment creation#439
Producdevity merged 2 commits into
stagingfrom
refactor/comment-create-service

Conversation

@Producdevity

@Producdevity Producdevity commented Jun 6, 2026

Copy link
Copy Markdown
Owner

Closes #391.

Summary

  • Move handheld comment creation orchestration into ListingCommentService
  • Keep repository focused on comment/listing/user persistence helpers
  • Cover notification, analytics, spam, and missing-entity behavior in router tests

Validation

  • ./node_modules/.bin/vitest run src/server/api/routers/listings/comments.test.ts
  • ./node_modules/.bin/tsc --noEmit
  • ./node_modules/.bin/eslint src/server/api/routers/listings/comments.ts src/server/repositories/comments.repository.ts src/server/services/listing-comment.service.ts src/server/api/routers/listings/comments.test.ts

Summary by CodeRabbit

  • Tests

    • Expanded tests for comment creation and replies, including analytics stubs and async side-effect handling.
  • Bug Fixes

    • Ensures first-comment journey tracking runs only for a user’s true first comment.
    • Returns clear errors when a listing or parent comment is missing.
  • Chores

    • Reorganized comment creation into a dedicated service and repository helpers for better maintainability.

@vercel

vercel Bot commented Jun 6, 2026

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
emuready Ready Ready Preview, Comment Jun 6, 2026 5:15pm

Request Review

@coderabbitai

coderabbitai Bot commented Jun 6, 2026

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 2a393729-64fc-482b-9a2b-95f4e4c43f90

📥 Commits

Reviewing files that changed from the base of the PR and between b84bbcd and 5e4e835.

📒 Files selected for processing (2)
  • src/server/api/routers/listings/comments.test.ts
  • src/server/services/listing-comment.service.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/server/services/listing-comment.service.ts

Walkthrough

Comment creation logic was moved from the router into a new ListingCommentService. CommentsRepository gained existence/count helpers and a refactored create path. The router delegates to the service. Tests were extended to cover notifications, analytics, first-comment tracking, and error cases.

Changes

Comment Creation Service Refactoring

Layer / File(s) Summary
Repository data contracts and helpers
src/server/repositories/comments.repository.ts
CommentsRepository adds listingExists, commentExists, userExists, countByUser, refactors create to use handleDatabaseOperation, adds createForListing, and exports MinimalComment type alias.
Listing Comment Service with validations and analytics
src/server/services/listing-comment.service.ts
New ListingCommentService and CreateListingCommentInput validate listing/parent/user, run checkSpamContent (with optional human-verification token and headers), persist via CommentsRepository.createForListing, emit LISTING_COMMENTED or COMMENT_REPLIED, track engagement analytics, and conditionally fire userJourney.firstTimeAction when the user's comment count equals 1 (logging errors on tracking failures).
Router simplification / delegation
src/server/api/routers/listings/comments.ts
commentsRouter.create imports and delegates to ListingCommentService.create, passing userId from session and request headers, replacing prior inline creation logic.
Test coverage for service behavior
src/server/api/routers/listings/comments.test.ts
Adds analytics and logger stubs, PARENT_COMMENT_ID, flushBackgroundTasks() helper, and tests asserting notification emission and analytics for top-level vs reply comments, first-time journey tracking behavior, analytics failure logging while returning created comment, and error cases for missing listing or parent without invoking spam checks or creating comments.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title 'Refactor handheld comment creation' directly reflects the main change: moving comment creation logic into a service layer.
Description check ✅ Passed The description covers the main objectives, includes a fixed issue reference, validation steps, and lists changed files; however, it lacks a 'Type of change' checkbox and skips most testing checklist items.
Linked Issues check ✅ Passed The PR fulfills issue #391 by creating ListingCommentService to encapsulate comment creation logic and delegating from the router, removing inline orchestration from commentsRouter.create.
Out of Scope Changes check ✅ Passed All changes align with the refactor objective: test additions verify behavior, repository gains persistence helpers, and service encapsulates creation orchestration as required.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch refactor/comment-create-service
✨ Simplify code
  • Create PR with simplified code
  • Commit simplified code in branch refactor/comment-create-service

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
src/server/repositories/comments.repository.ts (1)

185-194: ⚡ Quick win

Inconsistent error handling in update method.

The new create method uses handleDatabaseOperation, but update does not. For consistency, consider wrapping update similarly—it can throw P2025 if the record doesn't exist.

♻️ Suggested fix
   async update(
     id: string,
     data: Prisma.CommentUpdateInput,
   ): Promise<Prisma.CommentGetPayload<{ include: typeof CommentsRepository.includes.minimal }>> {
-    return this.prisma.comment.update({
-      where: { id },
-      data,
-      include: CommentsRepository.includes.minimal,
-    })
+    return this.handleDatabaseOperation(
+      () =>
+        this.prisma.comment.update({
+          where: { id },
+          data,
+          include: CommentsRepository.includes.minimal,
+        }),
+      'Comment',
+    )
   }

Based on learnings: "Repositories should use project error helpers and consistent database operation handling"

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/server/repositories/comments.repository.ts` around lines 185 - 194, The
update method currently calls this.prisma.comment.update directly and lacks the
consistent error handling used elsewhere; wrap the call inside
handleDatabaseOperation to surface mapped project errors (e.g., convert Prisma
P2025 to a NotFound or project-specific error) and preserve the same return
type. Specifically, replace the direct call in CommentsRepository.update
(signature using id: string, data: Prisma.CommentUpdateInput and include:
CommentsRepository.includes.minimal) with a handleDatabaseOperation(async () =>
this.prisma.comment.update({...})) invocation so database errors are handled the
same way as in create.

Source: Learnings

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/server/services/listing-comment.service.ts`:
- Around line 54-58: The call to trackFirstComment after persisting the comment
can throw (e.g., countByUser DB error) and bubble up to the API caller; change
it to not break the request by making it fire-and-forget or catching errors:
either invoke trackFirstComment without awaiting (use void/async background) or
wrap the await in a try/catch and log the error so
emitCreatedNotification/trackCreatedComment and the returned comment are not
affected; reference the trackFirstComment function (and countByUser inside it)
and ensure any errors are logged rather than rethrown.

---

Nitpick comments:
In `@src/server/repositories/comments.repository.ts`:
- Around line 185-194: The update method currently calls
this.prisma.comment.update directly and lacks the consistent error handling used
elsewhere; wrap the call inside handleDatabaseOperation to surface mapped
project errors (e.g., convert Prisma P2025 to a NotFound or project-specific
error) and preserve the same return type. Specifically, replace the direct call
in CommentsRepository.update (signature using id: string, data:
Prisma.CommentUpdateInput and include: CommentsRepository.includes.minimal) with
a handleDatabaseOperation(async () => this.prisma.comment.update({...}))
invocation so database errors are handled the same way as in create.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 60ad175a-8939-4e60-b487-70dfe2a6713b

📥 Commits

Reviewing files that changed from the base of the PR and between 172be73 and b84bbcd.

📒 Files selected for processing (4)
  • src/server/api/routers/listings/comments.test.ts
  • src/server/api/routers/listings/comments.ts
  • src/server/repositories/comments.repository.ts
  • src/server/services/listing-comment.service.ts

Comment thread src/server/services/listing-comment.service.ts
@Producdevity Producdevity merged commit 24639ef into staging Jun 6, 2026
8 checks passed
@Producdevity Producdevity deleted the refactor/comment-create-service branch June 6, 2026 20:24
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

refactor: move comments router create logic to a repository

1 participant