Skip to content

Conversation

@Hajbo
Copy link
Collaborator

@Hajbo Hajbo commented Mar 17, 2025

Description

  • Article models and related migrations
  • Article endpoints
    • create
    • update
    • delete
    • get by slug
    • list
    • feed
  • Fix drop utility by dropping migrations table as well
  • Swagger id token auth. This closes feat: bearer authorization on swagger ui #107 as well. That PR didn't work out of the box (it uses an invalid token format, Bearer instead of Token as per specified in the docs), but it gave the inspiration.

PR Checklist (Please do not remove)

  • Read the CONTRIBUTING guide
  • Title this PR according to the type(scope): description or type: description format
  • Provide description sufficient to understand 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

    • Introduced full article management capabilities, including endpoints for listing, creating, updating, deleting articles, and fetching personalized feeds.
    • Enhanced API security with token authentication and persistent authorization.
    • Expanded the database to support new content types and user interactions, such as published and favorited articles.
    • Improved profile response handling to better reflect user following status.
    • Added a utility function for generating URL-friendly slugs.
    • Added a new configuration for database migrations and expanded the database schema to include articles and favorite articles.
  • Bug Fixes

    • Adjusted error handling in profile response generation to accommodate cases with no current user ID.

@Hajbo Hajbo requested a review from yamcodes March 17, 2025 17:14
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Mar 17, 2025

Walkthrough

This pull request makes several codebase updates across configuration, migration, and feature modules. The changes include reformatting VS Code settings, adding a migrations configuration and drop logic in the database, introducing new migration files and SQL scripts, and integrating a comprehensive articles feature (model, module, plugin, repository, schema, and service). Additional enhancements include improved Swagger bearer token support in the app module, error handling in authentication, schema export adjustments, and the inclusion of a slugify utility.

Changes

File(s) Change Summary
.vscode/settings.json Consolidated the "cSpell.words" array from multi-line to a single-line format.
db/config.ts, db/drop.ts Added a migrations configuration in defineConfig and updated the drop logic to include new tables with conditional dropping of the migrations table.
db/migrations/{0007_snapshot.json, _journal.json, 0007_thin_eternals.sql} Introduced new migration files: a JSON schema snapshot, a journal entry update, and a SQL migration that creates the articles and favorite_articles tables with corresponding constraints.
src/app.module.ts Enhanced Swagger UI configuration: added a tokenAuth security scheme with persist authorization enabled and integrated the new articlesPlugin.
src/articles/* Implemented the articles feature by introducing: a model (articles.model.ts), module (articles.module.ts), plugin (articles.plugin.ts), repository (articles.repository.ts), schema definitions (articles.schema.ts), and service (articles.service.ts).
src/auth/auth.service.ts Added the getOptionalUserIdFromHeader method to gracefully handle header-based user ID extraction.
src/database.providers.ts Updated the schema configuration to include articlesSchema alongside usersSchema.
src/profiles/* Revised profile definitions by switching from insertUserSchemaRaw to selectUserSchemaRaw and updating the generateProfileResponse method to accept a nullable user ID.
src/users/* Augmented the users model with new relationships (publishedArticles, favoriteArticles) and changed the export of selectUserSchemaRaw for broader access.
tsconfig.json Added a new path mapping alias: "@articles/*": ["./src/articles/*"].
src/utils/slugify.ts Introduced a new slugify utility function to generate URL-friendly slugs.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant ArticlesPlugin
    participant ArticlesService
    participant ArticlesRepository

    Client->>ArticlesPlugin: POST /articles (InsertArticleSchema)
    ArticlesPlugin->>ArticlesService: createArticle(requestData)
    ArticlesService->>ArticlesRepository: insertArticle(articleData)
    ArticlesRepository-->>ArticlesService: newArticle
    ArticlesService-->>ArticlesPlugin: formatArticle(newArticle)
    ArticlesPlugin-->>Client: Return Created Article (ReturnedArticleResponseSchema)
Loading

Assessment against linked issues

Objective Addressed Explanation
Implement bearer authorization on Swagger UI [#107]

Poem

I'm a rabbit hopping through the code,
Where changes bloom on every road.
Articles and migrations make me cheer,
Swagger bears a token, loud and clear.
With a twitch of my nose and a skip so spry,
I celebrate these changes as I pass by!

Tip

⚡🧪 Multi-step agentic review comment chat (experimental)
  • We're introducing multi-step agentic chat in review comments. This experimental feature enhances review discussions with the CodeRabbit agentic chat by enabling advanced interactions, including the ability to create pull requests directly from comments.
    - To enable this feature, set early_access to true under in the settings.
✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 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.

@Hajbo
Copy link
Collaborator Author

Hajbo commented Mar 17, 2025

@yamcodes I'm really not happy with the naming of things, any suggestion would be appreciated. Generally I don't like how the schemas and types are called across the codebase, maybe you have a better idea about it

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

🧹 Nitpick comments (8)
src/utils/slug.ts (1)

31-37: Consider adding a test for the slugify function.

The logic is sound, but slug generation is a critical component for article functionality since slugs are typically used in URLs. Adding unit tests would help ensure the function behaves as expected across different inputs, including edge cases like strings with multiple spaces, special characters, or non-Latin characters.

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

46-58: Consider uniqueness checks for slugs.
Because slug is derived from the title, collisions can occur if multiple articles share similar titles. Ensure that the repository throws or handles any uniqueness constraint violation.


60-82: Ensure concurrency safety for slug updates.
When updating an article’s title, the slug changes. If multiple updates happen concurrently, consider whether you need an optimistic concurrency check or versioning to avoid race conditions.

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

55-72: Typographical error in summary.
Line 69 uses “Artifle Feed” instead of “Article Feed.” Update to maintain consistency.

- summary: 'Artifle Feed',
+ summary: 'Article Feed',
db/migrations/meta/0007_snapshot.json (1)

1-308: Align date/time column types for consistency.
The articles table uses timestamp for created_at and updated_at, while other tables (e.g., favorite_articles, user_follows, users) use date. Storing only the date may discard valuable time information and lead to inconsistencies. Consider using timestamp throughout if you rely on specific time details.

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

110-123: Confirm return value handling for non-existent slug.

The method returns null if no article is found for the given slug. Consider throwing an error or returning a more explicit message for a missing article to streamline error handling in the service layer.


146-168: Check if update has taken effect.

After performing the update query, consider verifying whether the article was actually updated (e.g., checking affected rows) and possibly return the updated article or a bespoke response if no rows were updated (meaning the article might not belong to the user or didn’t exist).


169-175: Return the deleted article or a custom message.

As with updates, providing immediate feedback about whether the article was deleted or not will help keep the API consumer informed. A response indicating that no records were affected can be useful if the article does not exist or the user is not the owner.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 06050a1 and ca6358e.

📒 Files selected for processing (21)
  • .vscode/settings.json (1 hunks)
  • db/config.ts (1 hunks)
  • db/drop.ts (2 hunks)
  • db/migrations/0007_elite_patriot.sql (1 hunks)
  • db/migrations/meta/0007_snapshot.json (1 hunks)
  • db/migrations/meta/_journal.json (1 hunks)
  • src/app.module.ts (2 hunks)
  • src/articles/articles.model.ts (1 hunks)
  • src/articles/articles.module.ts (1 hunks)
  • src/articles/articles.plugin.ts (1 hunks)
  • src/articles/articles.repository.ts (1 hunks)
  • src/articles/articles.schema.ts (1 hunks)
  • src/articles/articles.service.ts (1 hunks)
  • src/auth/auth.service.ts (1 hunks)
  • src/database.providers.ts (2 hunks)
  • src/profiles/profiles.schema.ts (2 hunks)
  • src/profiles/profiles.service.ts (1 hunks)
  • src/users/users.model.ts (2 hunks)
  • src/users/users.schema.ts (1 hunks)
  • src/utils/slug.ts (1 hunks)
  • tsconfig.json (1 hunks)
🔇 Additional comments (45)
.vscode/settings.json (1)

18-18: Format change for cSpell.words looks good.

The consolidation of the spell checker words to a single line is a simple formatting change with no functional impact.

tsconfig.json (1)

40-40: Path mapping for articles module properly configured.

This addition follows the project's established pattern for path aliases and will help maintain clean imports for the new articles module.

db/migrations/meta/_journal.json (1)

54-59: Migration entry correctly added to journal.

This new migration entry for "0007_elite_patriot" follows the sequential indexing pattern of previous migrations and appears to be the database changes supporting the article functionality mentioned in the PR summary.

src/utils/slug.ts (1)

26-39: Slug generation utility looks good with proper attribution.

The slugify function appears well-implemented with appropriate character normalization, accent removal, and formatting for URL-friendly slugs. The MIT license and reference links to the original sources are properly included.

db/config.ts (1)

22-26: Explicitly defined migration configuration improves clarity.

The addition of explicit migration configuration enhances code readability by clearly defining where migration metadata is stored, rather than relying on default settings.

src/database.providers.ts (2)

1-1: Import for the new articles schema added.

This import correctly brings in the articles schema definitions needed for database setup.


12-12: Schema configuration updated to include articles.

The database schema configuration has been properly extended to include both users and articles schemas, which is essential for enabling the article-related database operations.

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

1-9: Imports for article module dependencies established.

All necessary dependencies for the article module are properly imported, including repositories, services, and the Elysia framework.


10-24: Well-structured setup function using dependency injection.

The setupArticles function follows good software architecture practices:

  1. Creates repository instances first
  2. Injects repositories into services, establishing proper dependency chains
  3. Returns an Elysia instance with appropriate state for route handlers

This approach maintains clean separation of concerns and facilitates testing.

db/drop.ts (3)

3-4: Required imports for article tables and database configuration added.

The imports for article-related tables and database configuration have been correctly added to support the enhanced drop functionality.


8-8: Table drop list updated to include article tables.

The table array has been properly updated to include the new article-related tables, ensuring they're dropped when the database is reset.


22-28: Migration table drop logic added.

Good addition to handle the migrations table cleanup. This addresses the issue mentioned in the PR objectives where the migrations table needed to be dropped as well.

Note that dropping the migrations table will cause all migrations to be re-applied if the system is restarted, as the migration history will be lost. Ensure this is the intended behavior.

src/users/users.model.ts (2)

1-1: Good addition of imports for article-related models.

The import of articles and favoriteArticles is correctly added from the articles model, which will be needed for the new relationships defined in this file.


28-29: Well-structured relationship modeling for user-article connections.

These new relationships appropriately establish the connections between users and articles:

  1. publishedArticles links users to the articles they've authored
  2. favoriteArticles connects users to the articles they've favorited

The relationship naming is clear and follows the established pattern in the codebase. This implementation aligns perfectly with the PR objective of adding article functionality.

src/profiles/profiles.schema.ts (3)

5-5: Good update to import the proper schema.

Switching from insertUserSchemaRaw to selectUserSchemaRaw is appropriate since profiles are retrieved data rather than data being inserted.


14-14: Correctly uses the imported select schema.

Using selectUserSchemaRaw instead of insertUserSchemaRaw in the Type.Omit is the right approach for defining returned profile data structure.


21-23: Minor formatting improvement.

The addition of trailing commas improves code consistency and makes future additions to this object cleaner (preventing git diff issues when adding new properties).

src/users/users.schema.ts (1)

49-49: Good export of the select schema.

Making selectUserSchemaRaw available for import in other modules is necessary for its usage in the profiles schema. This change correctly supports the modifications made in src/profiles/profiles.schema.ts.

src/auth/auth.service.ts (1)

95-102: Well-implemented optional user ID retrieval.

This new method elegantly handles the case where authentication is optional, returning the user ID when available and null otherwise. It properly reuses the existing getUserFromHeaders method while adding appropriate error handling for the optional case.

This approach is valuable for features like viewing articles where behavior might differ between authenticated and anonymous users without requiring authentication.

src/profiles/profiles.service.ts (1)

55-69: Good update to handle optional user IDs

The modification to accept null for currentUserId and the conditional logic to handle this case is a good improvement. This change makes the profile service more flexible, allowing it to generate profile responses for both authenticated and unauthenticated users.

  async generateProfileResponse(
    user: Profile,
-   currentUserId: number,
+   currentUserId: number | null,
  ): Promise<ParsedProfileSchema> {
    return {
      profile: {
        bio: user.bio,
        image: user.image,
        username: user.username,
-       following: !!user.followers.find(
-           (follower) => follower.followerId === currentUserId,
-         ),
+       following:
+         currentUserId == null
+           ? false
+           : !!user.followers.find(
+               (follower) => follower.followerId === currentUserId,
+             ),
      },
    };
  }

This change properly handles cases where profile information needs to be retrieved without a logged-in user context (returning following: false).

src/app.module.ts (4)

1-1: Adding the articles plugin import

Good addition to support the new articles functionality.


40-54: Proper Swagger authentication configuration

The addition of security schemes for token authentication in Swagger is well-implemented. The description correctly instructs users to prefix tokens with "Token" rather than "Bearer", which aligns with the PR objectives mentioning fixing the token authentication format.


57-59: Good UX improvement with persistAuthorization

Setting persistAuthorization: true improves the developer experience by maintaining the authorization state across Swagger UI requests.


62-64: Adding the articles plugin to the API group

The articles plugin is correctly integrated into the API group alongside the existing plugins.

db/migrations/0007_elite_patriot.sql (3)

1-12: Well-structured articles table

The articles table has all necessary fields with appropriate constraints:

  • Primary key on id
  • Unique constraint on slug (important for URL-friendly identifiers)
  • Required fields for content (title, description, body)
  • Array type for tags with default empty array
  • Proper timestamp fields for created_at and updated_at
  • Foreign key to connect articles to their authors

This structure aligns well with standard article management requirements.


14-20: Well-designed favorites relationship table

The favorite_articles table correctly implements a many-to-many relationship between users and articles with:

  • Composite primary key on (article_id, user_id)
  • Appropriate timestamp fields

This design efficiently tracks which users have favorited which articles.


22-24: Appropriate cascade delete constraints

The foreign key constraints with cascade delete behavior are correctly implemented:

  • Deleting a user will delete their authored articles and favorites
  • Deleting an article will delete its favorites

This ensures referential integrity while preventing orphaned records.

src/articles/articles.model.ts (4)

14-26: Well-structured articles table model

The Drizzle ORM model for articles is properly defined with all necessary fields and constraints matching the SQL migration. The model includes appropriate references to the users table for the author relationship.


28-37: Proper article relations configuration

The article relations are well-configured:

  • One-to-one relation with users for the author
  • Many-to-many relation with users through the favoriteArticles table

This provides a good foundation for querying article data with related entities.


39-52: Correct implementation of favorite_articles junction table

The favoriteArticles table properly implements a many-to-many relationship between users and articles with:

  • References to both articles and users tables
  • Composite primary key on (articleId, userId)
  • Appropriate timestamp fields
  • Cascade delete constraints

This matches the SQL migration and follows Drizzle ORM best practices.


54-68: Well-defined favorite article relations

The relations for the favoriteArticles table are correctly set up:

  • One-to-one relation with the articles table
  • One-to-one relation with the users table
  • Appropriate relation names for bidirectional navigation

This allows for efficient querying of favorite articles with their related articles and users.

src/articles/articles.service.ts (5)

1-14: Imports look good.
No issues found with the import statements.


21-36: Verify the accuracy of articlesCount.
Currently, articlesCount is set to results.length, which only reflects the size of the fetched subset (limited by offset and limit). If you want to provide the total number of matching articles in the database, consider having the repository return the total instead.


38-44: Well-structured error handling.
Throwing a NotFoundError here is appropriate.


84-97: Deletion logic appears sound.
The authorization check is clear, and the final JSON response is straightforward.


99-124: Confirm favoritedBy always returns an array.
If favoritedBy could be undefined, the code would throw an error. Make sure the repository or mapping layer consistently returns an empty array instead of null or undefined.

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

1-12: No issues with initial imports.
All imports are appropriately scoped.


13-38: Plugin setup is coherent.
Establishing the /articles group with relevant tags is clear and well-documented.


39-54: Create Article endpoint looks good.
The route enforces authentication and validates the body schema properly.


73-83: Slug route retrieval is well-structured.
The path parameter is retrieved and handled properly.


84-100: Update endpoint logic is consistent.
Authentication, request body validation, and pass-through to the service are handled neatly.


101-116: Delete endpoint approach is clear.
The route ensures authentication and calls the corresponding service method.

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

1-9: Ensure consistent usage of path aliases.

Lines 6-7 use @/users/users.model vs. @articles/articles.model; please verify all import aliases to maintain consistency or confirm that these aliases are intentionally configured per the build system.

#!/bin/bash
# Description: Verify that all import paths follow a consistent alias pattern.
rg --sort=file "from '@" src
src/articles/articles.schema.ts (2)

19-23: Clarify slug creation in ArticleToCreate.

The schema includes slug: string, which may be set externally or computed upon insertion. Verify who owns slug generation logic, or consider omitting it if the logic is purely back-end-driven.


43-55: Validate author’s field types in ReturnedArticleSchema.

Within the composite schema, you are explicitly returning strings for author.bio, author.image, and author.username. Confirm that these fields are always present and non-null in the database. If they can be null, consider making them optional or providing a fallback value.

@yamcodes
Copy link
Contributor

yamcodes commented Mar 17, 2025

@yamcodes I'm really not happy with the naming of things, any suggestion would be appreciated. Generally I don't like how the schemas and types are called across the codebase, maybe you have a better idea about it

First, I hate hearing that you're "really not happy" 😭 so I'd do anything I can to change that!

Second, this is another thing I learned in the past year and half and formed an opinion on - and it pretty much aligns perfectly with colinhacks' here, I think he makes a great case: colinhacks/zod#3285 (comment)

it's not something we really need to tackle in this PR, but we can do another one to align the namings with this convention.

@yamcodes
Copy link
Contributor

yamcodes commented Mar 17, 2025

Small thing for your next PR, to make the checkpoints go from this:

image

to this:

image

You need to use - [x] (and not - [ x ]), it's the easiest to just open the PR and check the boxes by clicking them in the resulted post GUI checkboxes (they are clickable).

I've also edited the PR template to reflect that, in bed086e

Edit:

Holy shit, I cannot believe this SHA starts with "bed", what are the odds???

@yamcodes yamcodes linked an issue Mar 17, 2025 that may be closed by this pull request
@yamcodes yamcodes linked an issue Mar 17, 2025 that may be closed by this pull request
@yamcodes yamcodes added the enhancement New feature or request label Mar 18, 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: 6

🧹 Nitpick comments (9)
db/migrations/0007_thin_eternals.sql (2)

1-12: Consider adding indexes for improved query performance.

The articles table looks well-structured with appropriate constraints. To optimize query performance, consider adding indexes for fields that will be frequently used in WHERE clauses or JOINs, particularly the author_id field since you'll likely want to filter articles by author.

 CREATE TABLE "articles" (
 	"id" serial PRIMARY KEY NOT NULL,
 	"slug" text NOT NULL,
 	"title" text NOT NULL,
 	"description" text NOT NULL,
 	"body" text NOT NULL,
 	"tag_list" text[] DEFAULT '{}' NOT NULL,
 	"created_at" timestamp DEFAULT now() NOT NULL,
 	"updated_at" timestamp DEFAULT now() NOT NULL,
 	"author_id" integer NOT NULL,
 	CONSTRAINT "articles_slug_unique" UNIQUE("slug")
 );
+CREATE INDEX "articles_author_id_idx" ON "articles" ("author_id");
+CREATE INDEX "articles_created_at_idx" ON "articles" ("created_at" DESC);

14-20: Consider adding an index for user_id to optimize user-specific queries.

The composite primary key on article_id and user_id is good. For queries that filter favorites by user, an additional index on user_id alone would improve performance.

 CREATE TABLE "favorite_articles" (
 	"article_id" integer NOT NULL,
 	"user_id" integer NOT NULL,
 	"created_at" timestamp DEFAULT now() NOT NULL,
 	"updated_at" timestamp DEFAULT now() NOT NULL,
 	CONSTRAINT "favorite_articles_article_id_user_id_pk" PRIMARY KEY("article_id","user_id")
 );
+CREATE INDEX "favorite_articles_user_id_idx" ON "favorite_articles" ("user_id");
src/articles/articles.service.ts (2)

46-58: Potential slug collision not handled.

The slugify function may generate the same slug for similar titles. Consider adding logic to handle slug collisions by appending a unique identifier when a slug already exists.

 async createArticle(article: ArticleToCreateData, currentUserId: number) {
+  let baseSlug = slugify(article.title);
+  let slug = baseSlug;
+  let counter = 0;
+
+  // Check if slug already exists and generate a unique one if needed
+  while (await this.repository.slugExists(slug)) {
+    counter++;
+    slug = `${baseSlug}-${counter}`;
+  }
+
   const articleToCreate: ArticleToCreate = {
     ...article,
     tagList: article.tagList?.sort() || [],
     authorId: currentUserId,
-    slug: slugify(article.title),
+    slug,
   };
   const createdArticle = await this.repository.createArticle(articleToCreate);
   if (!createdArticle) {
     throw new BadRequestError('Article was not created');
   }
   return await this.generateArticleResponse(createdArticle, currentUserId);
 }

This would require adding a slugExists method to the repository.


72-82: Same slug collision issue during update.

Similar to the creation method, the update method doesn't handle potential slug collisions when updating the title.

   const newSlug = article.title
-    ? slugify(article.title)
+    ? await this.generateUniqueSlug(slugify(article.title), existingArticle.id)
     : existingArticle.slug;
   await this.repository.updateArticle(
     existingArticle.id,
     { ...article, slug: newSlug },
     currentUserId,
   );
   return this.findBySlug(newSlug);

You would need to add a helper method:

private async generateUniqueSlug(baseSlug: string, excludeArticleId?: number): Promise<string> {
  let slug = baseSlug;
  let counter = 0;
  
  while (await this.repository.slugExistsExcludingArticle(slug, excludeArticleId)) {
    counter++;
    slug = `${baseSlug}-${counter}`;
  }
  
  return slug;
}
src/articles/articles.plugin.ts (1)

69-70: Typo in feed endpoint summary.

There's a spelling error in the summary for the article feed endpoint.

 detail: {
-  summary: 'Artifle Feed',
+  summary: 'Article Feed',
 },
db/migrations/meta/0007_snapshot.json (2)

189-202: Consider using timestamp instead of date for user_follows timestamps.

I noticed that user_follows table uses the date type for timestamps, while the articles and favorite_articles tables use timestamp. This inconsistency could lead to precision issues when tracking follow relationships.

- "type": "date",
+ "type": "timestamp",

Also consider changing the default from CURRENT_DATE to now() for consistency with the articles tables.


289-302: Consider using timestamp instead of date for user timestamps.

Similar to the user_follows table, the users table also uses date type for timestamps instead of timestamp. For consistency and to capture time information:

- "type": "date",
+ "type": "timestamp",

And consider changing the default from CURRENT_DATE to now().

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

171-177: Add return type to deleteArticle method.

The deleteArticle method should have an explicit return type for better code clarity:

- async deleteArticle(slug: string, currentUserId: number) {
+ async deleteArticle(slug: string, currentUserId: number): Promise<void> {

142-146: Add error handling for article creation.

The createArticle method doesn't handle the case where insertion might fail. Consider adding error handling:

  async createArticle(article: ArticleToCreate) {
-   const results = await this.db.insert(articles).values(article).returning();
-   const newArticle = results[0];
-   return this.findById(newArticle.id);
+   try {
+     const results = await this.db.insert(articles).values(article).returning();
+     const newArticle = results[0];
+     return await this.findById(newArticle.id);
+   } catch (error) {
+     // Log the error or handle specific database errors
+     throw error;
+   }
  }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between ca6358e and c879e3a.

📒 Files selected for processing (9)
  • db/drop.ts (2 hunks)
  • db/migrations/0007_thin_eternals.sql (1 hunks)
  • db/migrations/meta/0007_snapshot.json (1 hunks)
  • db/migrations/meta/_journal.json (1 hunks)
  • src/articles/articles.model.ts (1 hunks)
  • src/articles/articles.plugin.ts (1 hunks)
  • src/articles/articles.repository.ts (1 hunks)
  • src/articles/articles.service.ts (1 hunks)
  • src/utils/slugify.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • db/drop.ts
  • db/migrations/meta/_journal.json
  • src/articles/articles.model.ts
🧰 Additional context used
🧠 Learnings (1)
src/articles/articles.repository.ts (1)
Learnt from: Hajbo
PR: agnyz/bedstack#129
File: src/articles/articles.repository.ts:13-108
Timestamp: 2025-03-17T17:22:55.819Z
Learning: When using Drizzle ORM with nullable parameters in SQL expressions, handling null checks in TypeScript before constructing the SQL query can help avoid type inference issues, rather than using SQL CASE WHEN statements.
🧬 Code Definitions (2)
src/articles/articles.plugin.ts (2)
src/articles/articles.module.ts (1) (1)
  • setupArticles (10-24)
src/articles/articles.schema.ts (7) (7)
  • ListArticlesQuerySchema (80-87)
  • ReturnedArticleListSchema (89-92)
  • InsertArticleSchema (10-17)
  • ReturnedArticleResponseSchema (57-59)
  • ArticleFeedQuerySchema (76-79)
  • UpdateArticleSchema (25-34)
  • DeleteArticleResponse (96-99)
src/articles/articles.repository.ts (4)
src/database.providers.ts (2) (2)
  • db (11-14)
  • Database (15-15)
src/users/users.model.ts (2) (2)
  • users (12-23)
  • userFollows (32-45)
src/articles/articles.model.ts (2) (2)
  • articles (14-26)
  • favoriteArticles (39-52)
src/articles/articles.schema.ts (2) (2)
  • ArticleToCreate (20-23)
  • ArticleToUpdate (39-41)
🔇 Additional comments (10)
src/utils/slugify.ts (2)

26-39: Nice implementation of the slugify utility.

The slugify function looks well-implemented with good handling of accents and special characters. I particularly like the use of Unicode normalization to separate base characters from diacritical marks.

A couple of suggestions for future enhancement:

  1. You might want to add collision handling if multiple articles end up with the same slug
  2. Consider adding a maximum length parameter to prevent overly long slugs

32-33: The biome-ignore comment explains the false positive.

Good practice to include the reason for the linter directive. This helps future maintainers understand why the exception was necessary.

db/migrations/0007_thin_eternals.sql (1)

22-24: Foreign key constraints look good.

The cascade delete behavior is appropriate here - when an article or user is deleted, related favorites should also be removed. This prevents orphaned records.

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

23-38: Consistent route paths for cleaner API.

In previous review discussions, there was a comment about trailing slashes. For consistency, it would be better to choose one approach (with or without trailing slashes) and apply it throughout the API.


27-30: Auth service API could be simplified.

As noted in a previous review comment, the way authentication is handled could be improved. Consider refactoring the auth service to accept the full request object or implement a more idiomatic approach using Elysia's features.


13-19: Well-organized plugin structure.

The use of Elysia's group feature to organize routes under the '/articles' path is well-implemented. The tagging for documentation purposes is also a good practice.

db/migrations/meta/0007_snapshot.json (1)

1-339: LGTM: Database schema snapshot looks well-structured.

The schema defines four tables with appropriate relationships and constraints:

  • articles with a unique slug constraint and foreign key to users
  • favorite_articles with a composite primary key and proper cascade behaviors
  • user_follows with appropriate relationship constraints
  • users with unique constraints on email and username

Good job setting up the relationships and constraints to maintain data integrity.

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

40-43: Handle possible null currentUserId before constructing SQL expression.

When currentUserId is null, this could lead to type inference issues with Drizzle ORM.

Based on the previous discussion and learnings, it's better to handle the null check in TypeScript:

- authorFollowing:
-   sql<boolean>`coalesce(${currentUserId} = any(array_agg(user_follows.follower_id)), false)`.as(
-     'authorFollowing',
-   ),
+ authorFollowing:
+   (currentUserId === null
+     ? sql<boolean>`false`
+     : sql<boolean>`coalesce(${currentUserId} = any(array_agg(user_follows.follower_id)), false)`
+   ).as('authorFollowing'),

63-66: Handle possible null currentUserId before constructing SQL expression.

Similar to the previous instance, the null check for currentUserId should be handled in TypeScript:

- favorited:
-   sql<boolean>`coalesce(${currentUserId} = any(array_agg(favorite_articles.user_id)), false)`.as(
-     'favorited',
-   ),
+ favorited:
+   (currentUserId === null
+     ? sql<boolean>`false`
+     : sql<boolean>`coalesce(${currentUserId} = any(array_agg(favorite_articles.user_id)), false)`
+   ).as('favorited'),

153-161: Simplify object transformation with a utility function.

The reduce operation is harder to read and understand at a glance. Consider using a utility function like shake to filter out undefined values.

- const valuesToSet = Object.entries(article).reduce(
-   (acc: { [key: string]: string | string[] | Date }, [key, value]) => {
-     if (value !== undefined) {
-       acc[key] = value;
-     }
-     return acc;
-   },
-   {},
- );
+ const valuesToSet = { ...shake(article) };

Where shake can be imported from a utility library like Radashi.

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: 2

♻️ Duplicate comments (1)
src/articles/articles.repository.ts (1)

33-49: 🛠️ Refactor suggestion

Handle null currentUserId in TypeScript rather than SQL.

Based on the learnings from previous discussions, you should handle the null check for currentUserId in TypeScript before constructing the SQL to avoid type inference issues with Drizzle ORM.

const authorsWithFollowersCTE = this.db.$with('authorsWithFollowers').as(
  this.db
    .select({
      authorId: users.id,
      authorUsername: users.username,
      authorBio: users.bio,
      authorImage: users.image,
-     authorFollowing:
-       sql<boolean>`coalesce(${currentUserId} = any(array_agg(user_follows.follower_id)), false)`.as(
-         'authorFollowing',
-       ),
+     authorFollowing: currentUserId === null
+       ? sql<boolean>`false`.as('authorFollowing')
+       : sql<boolean>`coalesce(${currentUserId} = any(array_agg(user_follows.follower_id)), false)`.as(
+           'authorFollowing',
+         ),
    })
    .from(users)
    .leftJoin(userFollows, eq(users.id, userFollows.followedId))
    .where(and(...authorFilters))
    .groupBy(users.id),
);
🧹 Nitpick comments (3)
src/articles/articles.service.ts (2)

39-39: Consider passing the currentUserId to the generateArticleResponse method.

When finding an article by slug, you're passing null for the currentUserId. If the endpoint might be called by authenticated users, consider extracting the user ID from the request headers.


56-78: The updateArticle implementation looks solid but return value could be improved.

The implementation correctly checks for article existence and author permissions before updating. However, consider adding error handling and updating the method to return the updated article directly from the repository.

async updateArticle(
  slug: string,
  article: ArticleToUpdateRequest,
  currentUserId: number,
) {
  const existingArticle = await this.repository.findBySlug(slug);
  if (!existingArticle) {
    throw new NotFoundError('Article not found');
  }
  if (existingArticle.authorId !== currentUserId) {
    throw new AuthorizationError('Only the author can update the article');
  }

  const newSlug = article.title
    ? slugify(article.title)
    : existingArticle.slug;
-  await this.repository.updateArticle(
-    existingArticle.id,
-    { ...article, slug: newSlug },
-    currentUserId,
-  );
-  return this.findBySlug(newSlug);
+  try {
+    const updatedArticle = await this.repository.updateArticle(
+      existingArticle.id,
+      { ...article, slug: newSlug },
+      currentUserId,
+    );
+    return await this.generateArticleResponse(updatedArticle, currentUserId);
+  } catch (error) {
+    console.error('Error updating article:', error);
+    throw error;
+  }
}
src/articles/articles.repository.ts (1)

177-183: Add error handling to deleteArticle.

Consider adding error handling to the deleteArticle method to catch and properly handle errors from the database operation.

async deleteArticle(slug: string, currentUserId: number) {
-  return await this.db
-    .delete(articles)
-    .where(
-      and(eq(articles.slug, slug), eq(articles.authorId, currentUserId)),
-    );
+  try {
+    return await this.db
+      .delete(articles)
+      .where(
+        and(eq(articles.slug, slug), eq(articles.authorId, currentUserId)),
+      );
+  } catch (error) {
+    console.error('Error deleting article:', error);
+    throw error;
+  }
}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between c879e3a and d811f95.

📒 Files selected for processing (3)
  • src/articles/articles.repository.ts (1 hunks)
  • src/articles/articles.service.ts (1 hunks)
  • src/auth/auth.service.ts (1 hunks)
🧰 Additional context used
🧠 Learnings (1)
src/articles/articles.repository.ts (1)
Learnt from: Hajbo
PR: agnyz/bedstack#129
File: src/articles/articles.repository.ts:13-108
Timestamp: 2025-03-17T17:22:55.819Z
Learning: When using Drizzle ORM with nullable parameters in SQL expressions, handling null checks in TypeScript before constructing the SQL query can help avoid type inference issues, rather than using SQL CASE WHEN statements.
🧬 Code Definitions (3)
src/auth/auth.service.ts (1)
src/errors.ts (1) (1)
  • AuthenticationError (3-9)
src/articles/articles.service.ts (4)
src/articles/articles.repository.ts (1) (1)
  • ArticlesRepository (10-184)
src/profiles/profiles.service.ts (1) (1)
  • ProfilesService (6-73)
src/articles/articles.schema.ts (6) (6)
  • ReturnedArticleList (94-94)
  • ArticleToCreateData (19-19)
  • ArticleToCreate (20-23)
  • ArticleToUpdateRequest (36-38)
  • ArticleInDb (66-72)
  • ReturnedArticleResponse (62-64)
src/utils/slugify.ts (1) (1)
  • slugify (26-39)
src/articles/articles.repository.ts (4)
src/database.providers.ts (2) (2)
  • db (11-14)
  • Database (15-15)
src/users/users.model.ts (2) (2)
  • users (12-23)
  • userFollows (32-45)
src/articles/articles.model.ts (2) (2)
  • articles (14-26)
  • favoriteArticles (39-52)
src/articles/articles.schema.ts (2) (2)
  • ArticleToCreate (20-23)
  • ArticleToUpdate (39-41)
🔇 Additional comments (6)
src/auth/auth.service.ts (1)

95-103: The implementation of optional user authentication looks good.

The method properly handles authentication errors by returning null when an AuthenticationError occurs, while still propagating other types of errors. This approach allows for optional authentication in endpoints that can work with both authenticated and unauthenticated users.

src/articles/articles.service.ts (1)

113-116: No need for the null check in the favorited check.

While adding a null check for currentUserId in the favorited condition would make the code more explicit, it's functionally unnecessary since comparing with null using === already returns false correctly.

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

106-113: Good implementation of pagination with count.

The implementation correctly separates the limited result query from the count query, ensuring accurate pagination. This is a robust approach that will work correctly even with large datasets.


116-130: Add explicit column selections to findBySlug.

For clarity and to ensure all necessary fields are included, add explicit column selections to the findBySlug method.

async findBySlug(slug: string) {
  const result = await this.db.query.articles.findFirst({
    where: eq(articles.slug, slug),
+   columns: {
+     id: true,
+     slug: true,
+     title: true,
+     description: true,
+     body: true,
+     tagList: true,
+     createdAt: true,
+     updatedAt: true,
+     authorId: true,
+   },
    with: {
      author: {
        with: {
          followers: true,
        },
      },
      favoritedBy: true,
    },
  });
  if (!result) return null;
  return result;
}

132-146: Add explicit column selections to findById.

Similarly, add explicit column selections to the findById method for consistency and clarity.

async findById(id: number) {
  const result = await this.db.query.articles.findFirst({
    where: eq(articles.id, id),
+   columns: {
+     id: true,
+     slug: true,
+     title: true,
+     description: true,
+     body: true,
+     tagList: true,
+     createdAt: true,
+     updatedAt: true,
+     authorId: true,
+   },
    with: {
      author: {
        with: {
          followers: true,
        },
      },
      favoritedBy: true,
    },
  });
  if (!result) return null;
  return result;
}

154-175: Simplify the updateArticle method.

The current approach using reduce to filter out undefined values works, but a more straightforward approach would be clearer and easier to maintain.

async updateArticle(
  articleId: number,
  article: ArticleToUpdate,
  currentUserId: number,
) {
-  const valuesToSet = Object.entries(article).reduce(
-    (acc: { [key: string]: string | string[] | Date }, [key, value]) => {
-      if (value !== undefined) {
-        acc[key] = value;
-      }
-      return acc;
-    },
-    {},
-  );
-  valuesToSet.updatedAt = new Date();
+  // Create a new object without undefined values
+  const valuesToSet = Object.fromEntries(
+    Object.entries(article).filter(([_, value]) => value !== undefined)
+  );
+  valuesToSet.updatedAt = new Date();
  await this.db
    .update(articles)
    .set(valuesToSet)
    .where(
      and(eq(articles.id, articleId), eq(articles.authorId, currentUserId)),
    );
+  // Return the updated article
+  return this.findById(articleId);
}

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

♻️ Duplicate comments (4)
src/articles/articles.repository.ts (4)

53-56: ⚠️ Potential issue

Handle possible null currentUserId in authorFollowing expression.

When currentUserId is null, the expression could produce unexpected behavior. The SQL expression isn't handling the null case properly.

Handle the null check in TypeScript rather than SQL to avoid type inference issues with Drizzle:

-authorFollowing:
-  sql<boolean>`coalesce(${currentUserId} = any(array_agg(user_follows.follower_id)), false)`.as(
-    'authorFollowing',
-  ),
+authorFollowing: currentUserId === null
+  ? sql<boolean>`false`.as('authorFollowing')
+  : sql<boolean>`coalesce(${currentUserId} = any(array_agg(user_follows.follower_id)), false)`.as(
+      'authorFollowing',
+    ),

76-79: ⚠️ Potential issue

Handle possible null currentUserId in favorited expression.

Similar to the authorFollowing expression, the favorited expression should handle null currentUserId in TypeScript.

Apply the same pattern as suggested for authorFollowing:

-favorited:
-  sql<boolean>`coalesce(${currentUserId} = any(array_agg(favorite_articles.user_id)), false)`.as(
-    'favorited',
-  ),
+favorited: currentUserId === null
+  ? sql<boolean>`false`.as('favorited')
+  : sql<boolean>`coalesce(${currentUserId} = any(array_agg(favorite_articles.user_id)), false)`.as(
+      'favorited',
+    ),

132-146: 🛠️ Refactor suggestion

Include explicit column selection in findBySlug.

The findBySlug method doesn't explicitly select columns, which could lead to missing fields in the returned data.

Add explicit column selection to ensure all necessary fields are included:

async findBySlug(slug: string) {
  const result = await this.db.query.articles.findFirst({
    where: eq(articles.slug, slug),
+   columns: {
+     id: true,
+     slug: true,
+     title: true,
+     description: true,
+     body: true,
+     tagList: true,
+     createdAt: true,
+     updatedAt: true,
+   },
    with: {
      author: {
        with: {
          followers: true,
        },
      },
      favoritedBy: true,
    },
  });
  if (!result) return null;
  return result;
}

148-162: 🛠️ Refactor suggestion

Include explicit column selection in findById.

Similar to findBySlug, the findById method should explicitly select all needed columns.

Add explicit column selection:

async findById(id: number) {
  const result = await this.db.query.articles.findFirst({
    where: eq(articles.id, id),
+   columns: {
+     id: true,
+     slug: true,
+     title: true,
+     description: true,
+     body: true,
+     tagList: true,
+     createdAt: true,
+     updatedAt: true,
+   },
    with: {
      author: {
        with: {
          followers: true,
        },
      },
      favoritedBy: true,
    },
  });
  if (!result) return null;
  return result;
}
🧹 Nitpick comments (4)
db/migrations/meta/0007_snapshot.json (2)

1-307: Database schema structure looks well-designed, but has timestamp vs date inconsistency.

The database schema is well-structured with appropriate relationships and constraints. However, there's an inconsistency in date/time handling:

  • articles and favorite_articles tables use timestamp type (lines 50, 57, 111, 118)
  • user_follows and users tables use date type (lines 174, 181, 263, 270)

This inconsistency could lead to subtle bugs where some entities track time with precision while others only track dates.

Consider standardizing on timestamp for all temporal columns to ensure consistency and retain time precision across all tables.


69-70: Consider adding indexes on foreign key columns for performance.

The schema doesn't define any indexes on foreign key columns that would be frequently used in JOIN operations or WHERE clauses. This could impact query performance, especially as the database grows.

Consider adding indexes on foreign key columns and other frequently queried columns:

  • articles.author_id
  • favorite_articles.article_id and favorite_articles.user_id
  • user_follows.followed_id and user_follows.follower_id

Also applies to: 276-277

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

193-199: Add error handling and check for deletion success.

The deleteArticle method doesn't check if the deletion was successful and has unnecessary await in the return statement.

Improve error handling and check for deletion success:

async deleteArticle(slug: string, currentUserId: number) {
-  return await this.db
+  const result = await this.db
    .delete(articles)
    .where(
      and(eq(articles.slug, slug), eq(articles.authorId, currentUserId)),
    );
+  return result.rowsAffected > 0;
}

6-7: Ensure consistent import paths.

Import statements mix @/ and @articles/ path aliases, which can be confusing.

Standardize import path aliases for consistency:

-import { userFollows, users } from '@/users/users.model';
-import { articles, favoriteArticles } from '@articles/articles.model';
+import { articles, favoriteArticles } from '@/articles/articles.model';
+import { userFollows, users } from '@/users/users.model';
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between d811f95 and 100453b.

📒 Files selected for processing (5)
  • db/migrations/meta/0007_snapshot.json (1 hunks)
  • db/migrations/meta/_journal.json (1 hunks)
  • src/articles/articles.plugin.ts (1 hunks)
  • src/articles/articles.repository.ts (1 hunks)
  • src/articles/articles.service.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • db/migrations/meta/_journal.json
  • src/articles/articles.service.ts
  • src/articles/articles.plugin.ts
🧰 Additional context used
🧠 Learnings (1)
src/articles/articles.repository.ts (1)
Learnt from: Hajbo
PR: agnyz/bedstack#129
File: src/articles/articles.repository.ts:13-108
Timestamp: 2025-03-17T17:22:55.819Z
Learning: When using Drizzle ORM with nullable parameters in SQL expressions, handling null checks in TypeScript before constructing the SQL query can help avoid type inference issues, rather than using SQL CASE WHEN statements.
🧬 Code Definitions (1)
src/articles/articles.repository.ts (4)
src/database.providers.ts (2) (2)
  • db (11-14)
  • Database (15-15)
src/users/users.model.ts (2) (2)
  • users (12-23)
  • userFollows (32-45)
src/articles/articles.model.ts (2) (2)
  • articles (14-26)
  • favoriteArticles (39-52)
src/articles/articles.schema.ts (2) (2)
  • ArticleToCreate (20-23)
  • ArticleToUpdate (39-41)

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

♻️ Duplicate comments (1)
src/articles/articles.repository.ts (1)

170-187: 🛠️ Refactor suggestion

Return the updated article from updateArticle method.

The updateArticle method doesn't return the updated article, making it difficult for callers to access the updated data.

Return the updated article after updating:

async updateArticle(
  articleId: number,
  article: ArticleToUpdate,
  currentUserId: number,
) {
  const filteredArticle = Object.fromEntries(
    Object.entries(article).filter(([_, value]) => value !== undefined),
  );
  await this.db
    .update(articles)
    .set({
      ...filteredArticle,
      updatedAt: new Date(),
    })
    .where(
      and(eq(articles.id, articleId), eq(articles.authorId, currentUserId)),
    );
+  
+  // Return the updated article
+  return this.findById(articleId);
}
🧹 Nitpick comments (2)
src/articles/articles.repository.ts (2)

189-195: Improve error handling for deleteArticle method.

The deleteArticle method doesn't check if the article exists or if the delete operation was successful.

Consider adding error handling and returning a more informative result:

async deleteArticle(slug: string, currentUserId: number) {
-  return await this.db
-    .delete(articles)
-    .where(
-      and(eq(articles.slug, slug), eq(articles.authorId, currentUserId)),
-    );
+  // First check if the article exists and belongs to the user
+  const article = await this.db.query.articles.findFirst({
+    where: and(eq(articles.slug, slug), eq(articles.authorId, currentUserId)),
+    columns: { id: true },
+  });
+  
+  if (!article) {
+    return { deleted: false, reason: 'Article not found or not owned by the user' };
+  }
+  
+  await this.db
+    .delete(articles)
+    .where(eq(articles.id, article.id));
+    
+  return { deleted: true };
}

1-196: Ensure proper transaction handling for database operations.

The repository methods perform individual database operations, but there's no transaction management for operations that might require atomicity.

Consider adding transaction support for operations that modify data:

// Example for createArticle
async createArticle(article: ArticleToCreate) {
  return await this.db.transaction(async (tx) => {
    const results = await tx.insert(articles).values(article).returning();
    const newArticle = results[0];
    
    // Perform any additional operations within the transaction
    
    return this.findById(newArticle.id);
  });
}

This ensures that all operations within the method either complete successfully or are rolled back in case of an error.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 100453b and e707eb6.

📒 Files selected for processing (1)
  • src/articles/articles.repository.ts (1 hunks)
🧰 Additional context used
🧠 Learnings (1)
src/articles/articles.repository.ts (1)
Learnt from: Hajbo
PR: agnyz/bedstack#129
File: src/articles/articles.repository.ts:13-108
Timestamp: 2025-03-17T17:22:55.819Z
Learning: When using Drizzle ORM with nullable parameters in SQL expressions, handling null checks in TypeScript before constructing the SQL query can help avoid type inference issues, rather than using SQL CASE WHEN statements.
🧬 Code Definitions (1)
src/articles/articles.repository.ts (4)
src/database.providers.ts (2) (2)
  • db (11-14)
  • Database (15-15)
src/users/users.model.ts (2) (2)
  • users (12-23)
  • userFollows (32-45)
src/articles/articles.model.ts (2) (2)
  • articles (14-26)
  • favoriteArticles (39-52)
src/articles/articles.schema.ts (2) (2)
  • ArticleToCreate (20-23)
  • ArticleToUpdate (39-41)
🔇 Additional comments (3)
src/articles/articles.repository.ts (3)

13-130: Handle null checks for currentUserId in SQL expressions.

The SQL expressions for authorsWithFollowers and articlesWithLikes might have unexpected behavior when currentUserId is null. Based on the retrieved learning, handling null checks in TypeScript is preferred over SQL CASE WHEN statements.

Apply TypeScript null checks before constructing the SQL expressions:

- authorFollowing:
-   sql<boolean>`coalesce(${currentUserId} = any(array_agg(user_follows.follower_id)), false)`.as(
-     'authorFollowing',
-   ),
+ authorFollowing: currentUserId === null
+   ? sql<boolean>`false`.as('authorFollowing')
+   : sql<boolean>`coalesce(${currentUserId} = any(array_agg(user_follows.follower_id)), false)`.as(
+       'authorFollowing',
+     ),

And similarly for the articlesWithLikes CTE:

- favorited:
-   sql<boolean>`coalesce(${currentUserId} = any(array_agg(favorite_articles.user_id)), false)`.as(
-     'favorited',
-   ),
+ favorited: currentUserId === null
+   ? sql<boolean>`false`.as('favorited')
+   : sql<boolean>`coalesce(${currentUserId} = any(array_agg(favorite_articles.user_id)), false)`.as(
+       'favorited',
+     ),

132-146: Add missing fields to findBySlug return data.

The findBySlug method doesn't explicitly include all necessary article fields which could lead to missing data.

Explicitly include all required fields:

async findBySlug(slug: string) {
  const result = await this.db.query.articles.findFirst({
    where: eq(articles.slug, slug),
+   columns: {
+     id: true,
+     slug: true,
+     title: true,
+     description: true,
+     body: true,
+     tagList: true,
+     createdAt: true,
+     updatedAt: true,
+   },
    with: {
      author: {
        with: {
          followers: true,
        },
      },
      favoritedBy: true,
    },
  });
  if (!result) return null;
  return result;
}

148-162: Add missing fields to findById return data.

Similar to the findBySlug method, the findById method doesn't explicitly include all necessary article fields.

Explicitly include all required fields:

async findById(id: number) {
  const result = await this.db.query.articles.findFirst({
    where: eq(articles.id, id),
+   columns: {
+     id: true,
+     slug: true,
+     title: true,
+     description: true,
+     body: true,
+     tagList: true,
+     createdAt: true,
+     updatedAt: true,
+   },
    with: {
      author: {
        with: {
          followers: true,
        },
      },
      favoritedBy: true,
    },
  });
  if (!result) return null;
  return result;
}

@Hajbo Hajbo merged commit 0ddb69b into main Mar 20, 2025
4 checks passed
@Hajbo Hajbo deleted the feature/articles-crud branch March 20, 2025 02:39
yamcodes pushed a commit that referenced this pull request Mar 20, 2025
 - Article models and related migrations
 - Article endpoints
   -  create
   - update
   - delete
   - get by slug
   - list
   - feed
 - Fix drop utility by dropping migrations table as well
- Swagger id token auth. This closes #107 as well. That PR didn't work
out of the box (it uses an invalid token format, Bearer instead of Token
as per specified in the
[docs](https://realworld-docs.netlify.app/specifications/backend/endpoints/)),
but it gave the inspiration.

- [x] Read the [CONTRIBUTING](
  https://github.com/agnyz/bedstack/blob/main/CONTRIBUTING.md) guide
- [x] Title this PR according to the `type(scope): description` or
`type: description` format
- [x] Provide description sufficient to understand the changes
introduced in this PR, and, if necessary, some screenshots
- [x] Reference an issue or discussion where the feature or changes have
been previously discussed
- [x] Add a failing test that passes with the changes introduced in this
PR, or explain why it's not feasible
- [x] Add documentation for the feature or changes introduced in this PR
to the docs; you can run them with `bun docs`

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

- **New Features**
- Introduced full article management capabilities, including endpoints
for listing, creating, updating, deleting articles, and fetching
personalized feeds.
- Enhanced API security with token authentication and persistent
authorization.
- Expanded the database to support new content types and user
interactions, such as published and favorited articles.
- Improved profile response handling to better reflect user following
status.
  - Added a utility function for generating URL-friendly slugs.
- Added a new configuration for database migrations and expanded the
database schema to include articles and favorite articles.

- **Bug Fixes**
- Adjusted error handling in profile response generation to accommodate
cases with no current user ID.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
yamcodes added a commit that referenced this pull request Mar 22, 2025
### Description

<!-- Provide a comprehensive description here about what your PR aims to
solve. -->

Implement comment feature for articles.

<!-- You may also add additional context -->

Builds on #129 so it's better to merge that first.

---

### PR Checklist

<!-- Please do not remove this section -->

<!-- Mark each item with an "x" ([ ] becomes [x]) -->

- [x] Read the Developer's Guide in
[CONTRIBUTING.md](https://github.com/agnyz/bedstack/blob/main/CONTRIBUTING.md)
- [x] Use a concise title to represent the changes introduced in this PR
- [x] Provide a detailed description of the changes introduced in this
PR, and, if necessary, some screenshots
- [x] Reference an issue or discussion where the feature or changes have
been previously discussed
- [x] Add a failing test that passes with the changes introduced in this
PR, or explain why it's not feasible
- [x] Add documentation for the feature or changes introduced in this PR
to the docs; you can run them with `bun docs`


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

- **New Features**
- Expanded article capabilities to include creation, updates, deletions,
and personalized feeds.
- Introduced full comment management, allowing users to add, view, and
delete comments on articles.
- Improved profile retrieval for a more dynamic and accurate display of
user information.
- Added functionality to manage favorited articles and their associated
comments.
- Enhanced schema definitions for articles and comments, providing a
robust framework for management.
  - New methods for retrieving user profiles based on user ID.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Hajbo <hajbodev@gmail.com>
Co-authored-by: Hajbo <35660161+Hajbo@users.noreply.github.com>
This was referenced Jun 7, 2025
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 Articles List and Feed features Implement Articles CRUD features

3 participants