Skip to content

Conversation

@aruaycodes
Copy link
Collaborator

@aruaycodes aruaycodes commented Mar 22, 2025

Description


PR Checklist

  • Read the Developer's Guide in CONTRIBUTING.md
  • Use a concise title to represent the changes introduced in this PR
  • Provide a detailed description of the changes introduced in this PR, and, if necessary, some screenshots
  • Reference an issue or discussion where the feature or changes have been previously discussed
  • Add a failing test that passes with the changes introduced in this PR, or explain why it's not feasible
  • Add documentation for the feature or changes introduced in this PR to the docs; you can run them with bun docs

Summary by CodeRabbit

  • New Features
    • Added the ability for authenticated users to favorite and unfavorite articles through new API endpoints.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Mar 22, 2025

Caution

Review failed

The head commit changed during the review from 2fd8b07 to 7f38fca.

Walkthrough

The changes introduce functionality for users to favorite and unfavorite articles in the application. This is achieved by adding new endpoints to the articles API, corresponding service and repository methods to handle the logic, and updating the database interactions accordingly. The new endpoints require authentication and allow users to mark or unmark articles as favorites, updating the state in the database and returning the updated article information. No functional changes were made to the main server setup.

Changes

File(s) Change Summary
src/articles/articles.plugin.ts Added POST and DELETE endpoints at /:slug/favorite for favoriting and unfavoriting articles with authentication.
src/articles/articles.repository.ts Added favoriteArticle and unfavoriteArticle methods to manage favorite status in the database.
src/articles/articles.service.ts Added service methods to call repository logic and handle errors for favoriting and unfavoriting articles.
src/main.ts Added a trailing blank line after the server listen statement; no functional changes.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant API (articles.plugin)
    participant Service
    participant Repository
    participant Database

    User->>API (articles.plugin): POST /:slug/favorite (with token)
    API (articles.plugin)->>Service: favoriteArticle(slug, userId)
    Service->>Repository: favoriteArticle(slug, userId)
    Repository->>Database: Insert favorite, fetch article
    Database-->>Repository: Article data
    Repository-->>Service: Article data
    Service-->>API (articles.plugin): Article response
    API (articles.plugin)-->>User: Article response

    User->>API (articles.plugin): DELETE /:slug/favorite (with token)
    API (articles.plugin)->>Service: unfavoriteArticle(slug, userId)
    Service->>Repository: unfavoriteArticle(slug, userId)
    Repository->>Database: Delete favorite, fetch article
    Database-->>Repository: Article data
    Repository-->>Service: Article data
    Service-->>API (articles.plugin): Article response
    API (articles.plugin)-->>User: Article response
Loading

Poem

In the warren of code, new features appear,
Now bunnies can favorite articles they hold dear.
With a flick of a paw, or a click of a key,
You can favorite or unfavorite, as easy as can be!
The endpoints are ready, the service is spry,
Hop in and try—give your favorites a try!
🥕✨


🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (2)
src/articles/articles.service.ts (2)

122-138: LGTM, but consider handling state more consistently

The implementation for favoriting an article is well-structured, but there's a potential consistency issue. The method generates the response from the database state and then manually modifies it. Consider refetching the article after favoriting to ensure the response reflects the actual database state.

 async favoriteArticle(slug: string, currentUserId: number) {
   const article = await this.repository.favoriteArticle(slug, currentUserId);
   const baseResponse = await this.generateArticleResponse(article, currentUserId);
   
   // If the article is already favorited, return the current state
   if (baseResponse.article.favorited) {
     return baseResponse;
   }

-  return {
-    article: {
-      ...baseResponse.article,
-      favorited: true,
-      favoritesCount: baseResponse.article.favoritesCount + 1,
-    },
-  };
+  // Refetch to get the updated state
+  const updatedArticle = await this.repository.findBySlug(slug);
+  return this.generateArticleResponse(updatedArticle!, currentUserId);
 }

140-156: Same refactoring suggestion as above

Similar to the favorite method, consider refetching the article to ensure the response reflects the actual database state rather than manually adjusting the values.

 async unfavoriteArticle(slug: string, currentUserId: number) {
   const article = await this.repository.unfavoriteArticle(slug, currentUserId);
   const baseResponse = await this.generateArticleResponse(article, currentUserId);
   
   // If the article is not favorited, return the current state
   if (!baseResponse.article.favorited) {
     return baseResponse;
   }

-  return {
-    article: {
-      ...baseResponse.article,
-      favorited: false,
-      favoritesCount: baseResponse.article.favoritesCount - 1,
-    },
-  };
+  // Refetch to get the updated state
+  const updatedArticle = await this.repository.findBySlug(slug);
+  return this.generateArticleResponse(updatedArticle!, currentUserId);
 }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between c862076 and f82bf94.

📒 Files selected for processing (4)
  • .gitignore (1 hunks)
  • src/articles/articles.plugin.ts (1 hunks)
  • src/articles/articles.repository.ts (2 hunks)
  • src/articles/articles.service.ts (1 hunks)
🧰 Additional context used
🧬 Code Definitions (2)
src/articles/articles.repository.ts (1)
src/articles/articles.model.ts (1) (1)
  • favoriteArticles (39-52)
src/articles/articles.plugin.ts (1)
src/articles/articles.schema.ts (1) (1)
  • ReturnedArticleResponseSchema (57-59)
🔇 Additional comments (6)
.gitignore (1)

47-47: LGTM!

Adding .qodo to the gitignore file is a straightforward change that prevents these files from being committed to the repository.

src/articles/articles.plugin.ts (2)

117-130: LGTM!

The POST endpoint for favoriting an article is well-implemented. It properly requires user authentication, extracts the necessary parameters, and follows the established pattern for error handling and response structure.


132-145: LGTM!

The DELETE endpoint for unfavoriting an article is properly implemented, requiring authentication and following the same pattern as other endpoints.

src/articles/articles.repository.ts (3)

9-10: LGTM!

The import of NotFoundError from 'elysia' is correctly added and is used in the new methods for error handling.


201-228: LGTM!

The favoriteArticle method is well-implemented with proper error handling and duplicate prevention. It checks if the article exists and ensures a user doesn't favorite the same article multiple times.


230-261: LGTM!

The unfavoriteArticle method is well-implemented with proper error handling and edge case consideration. It checks if the article exists and if the user has already favorited it before attempting to remove the favorite.

@aruaycodes aruaycodes changed the title feat: add favorite/unfavorite of articles feat: add favorite/unfavorite of articles Mar 22, 2025
@yamcodes yamcodes linked an issue Mar 22, 2025 that may be closed by this pull request
Copy link
Contributor

@yamcodes yamcodes left a comment

Choose a reason for hiding this comment

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

The repository logic needs to be fixed to handle favoriting and returning the updated state, the service level shouldn't be responsible to mask the issues of the repository level

@aruaycodes aruaycodes requested a review from yamcodes March 23, 2025 19:59
@yamcodes
Copy link
Contributor

Live testing shows that the operation returns outdated information - favoriting an article shows a favorite count of 0 and only once favoriting again it shows the updated state.

Same applies for unfavoriting. I can see that the operation works on the database level but the response is not updated.

I would recommended solving this at the repository level - meaning, the database call to favorite/unfavorite should already return the correct updated state (and not the one before the operation was done)

@yamcodes yamcodes added the enhancement New feature or request label Mar 25, 2025
@bedtime-coders bedtime-coders deleted a comment from coderabbitai bot Apr 11, 2025
@bedtime-coders bedtime-coders deleted a comment from coderabbitai bot Apr 11, 2025
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between f3bf4aa and edb869f.

📒 Files selected for processing (3)
  • .gitignore (1 hunks)
  • src/articles/articles.repository.ts (1 hunks)
  • src/main.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • .gitignore
  • src/articles/articles.repository.ts

Copy link
Contributor

@yamcodes yamcodes left a comment

Choose a reason for hiding this comment

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

Good job, according to my testing the PR gets the job done.

There are some things that are unnecessary and some improvements we can make

Comment on lines 213 to 231
async unfavoriteArticle(slug: string, currentUserId: number) {
const article = await this.findBySlug(slug);
if (!article) {
return null;
}

// Delete the favorite and get the updated article state
await this.db
.delete(favoriteArticles)
.where(
and(
eq(favoriteArticles.articleId, article.id),
eq(favoriteArticles.userId, currentUserId),
),
);

// Return the updated article state
return this.findBySlug(slug);
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Overall there are 1 or 3 db operations (depending if the article is found, or not)

I believe we can reduce this to 2 and even 1 op total.

@coderabbitai

Copy link
Contributor

Choose a reason for hiding this comment

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

@yamcodes You're absolutely right about the multiple DB operations. The current implementation has up to 3 database operations:

  1. Initial findBySlug
  2. Insert/delete operation
  3. Second findBySlug to get updated state

Here are two possible optimizations:

Option 1: Reduce to 2 operations

Keep the initial check but don't fetch the article twice:

async favoriteArticle(slug: string, currentUserId: number) {
  const article = await this.findBySlug(slug);
  if (!article) return null;

  await this.db
    .insert(favoriteArticles)
    .values({ articleId: article.id, userId: currentUserId })
    .onConflictDoNothing();
    
  // Instead of calling findBySlug again, update the article object
  const favorited = true;
  const favoritesCount = (article.favoritedBy?.length || 0) + 1;
  
  return {
    ...article,
    favoritedBy: [...(article.favoritedBy || []), { userId: currentUserId }],
  };
}

Option 2: Reduce to 1 operation (more advanced)

Use a transaction with a CTE to handle everything in one query:

async favoriteArticle(slug: string, currentUserId: number) {
  // Single operation that handles existence check, favorite action, and returns data
  const result = await this.db.transaction(async (tx) =

> {
    const articleResult = await tx.query.articles.findFirst({
      where: eq(articles.slug, slug)
    });
    
    if (!articleResult) return null;
    
    await tx
      .insert(favoriteArticles)
      .values({ articleId: articleResult.id, userId: currentUserId })
      .onConflictDoNothing();
    
    return tx.query.articles.findFirst({
      where: eq(articles.slug, slug),
      with: {
        author: {
          with: { followers: true }
        },
        favoritedBy: true
      }
    });
  });
  
  return result;
}

Which approach would you prefer to implement?

Co-authored-by: Yam Borodetsky <yam@yam.codes>
aruaycodes and others added 4 commits April 15, 2025 21:31
Co-authored-by: Yam Borodetsky <yam@yam.codes>
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
@yamcodes yamcodes merged commit e983b43 into main Apr 15, 2025
3 checks passed
@yamcodes yamcodes deleted the favorite-unfavorite branch April 15, 2025 16:38
@coderabbitai coderabbitai bot mentioned this pull request Jun 8, 2025
6 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Implement Article Favorite feature

3 participants