Skip to content

Add thread schema #210

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Jun 10, 2025
Merged

Add thread schema #210

merged 3 commits into from
Jun 10, 2025

Conversation

Behzad-rabiei
Copy link
Member

@Behzad-rabiei Behzad-rabiei commented Jun 10, 2025

Summary by CodeRabbit

  • New Features

    • Introduced support for thread entities, including new data models, schemas, and repository for managing threads within the application.
  • Tests

    • Added comprehensive unit tests to validate thread data and ensure correct model behavior.
  • Chores

    • Updated exports to include new thread-related modules and interfaces.
    • Added a rule file providing guidelines for the mongo-lib package.
  • Refactor

    • Reorganized import and export statements for improved code structure and consistency.
  • Documentation

    • Removed an outdated changelog entry for a previous feature.

Copy link

coderabbitai bot commented Jun 10, 2025

Walkthrough

This update introduces comprehensive support for "Thread" entities in a MongoDB-backed system. It adds TypeScript interfaces, a Mongoose schema and model, a repository for data access, and corresponding unit tests. The changes also include updates to module exports and import order, adjustments to asynchronous method signatures in other interfaces, and a new rule file for project guidelines.

Changes

File(s) Change Summary
.cursor/rules/mongo-lib.mdc Added a new rule file with metadata and project guidelines for the mongo-lib package.
CHANGELOG.md Removed the changelog entry for version 3.11.0 concerning the "upsert repo" feature.
src/interfaces/Thread.interface.ts Added TypeScript interfaces for thread entities, metadata, update payloads, and model methods.
src/interfaces/index.ts Exported Thread.interface from the interfaces index.
src/interfaces/Announcement.interface.ts Removed IAnnouncementMethods interface and simplified AnnouncementModel interface.
src/interfaces/Channel.interface.ts Changed softDelete method return type in IChannelMethods to Promise<void>.
src/interfaces/GuildMember.interface.ts Changed softDelete method return type in IGuildMemberMethods to Promise<void>.
src/interfaces/Role.interface.ts Changed softDelete method return type in IRoleMethods to Promise<void>.
src/interfaces/Platfrom.interface.ts Changed import statements from type-only to regular imports for Model, Types, and PlatformNames.
src/models/Thread.model.ts Created and exported the Mongoose model for Thread using the new schema.
src/models/index.ts Reordered imports and added Thread to the exported models.
src/models/schemas/Thread.schema.ts Added a new Mongoose schema for threads, including metadata and a softDelete instance method.
src/models/schemas/index.ts Reordered imports and added threadSchema to the exported schemas.
src/models/schemas/Channel.schema.ts Reordered imports and removed a comment from the permissionOverwrites field.
src/repositories/thread.repository.ts Added a repository class and factory for thread data access using the Thread model.
__tests__/unit/models/thread.model.test.ts Introduced unit tests for the Thread model, covering validation and edge cases.

Sequence Diagram(s)

sequenceDiagram
  participant App
  participant ThreadRepository
  participant MongooseModel
  participant MongoDB

  App->>ThreadRepository: create/update/find thread
  ThreadRepository->>MongooseModel: call model methods (e.g., create, find, update)
  MongooseModel->>MongoDB: execute database operation
  MongoDB-->>MongooseModel: return result
  MongooseModel-->>ThreadRepository: return document(s)
  ThreadRepository-->>App: return thread data
Loading

Poem

In burrows deep, a thread appears,
With models, schemas, tests—three cheers!
Repositories hop in line,
Interfaces looking mighty fine.
Now rabbits code with Mongo’s might,
Threading data left and right!
🐇✨

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

npm error Exit handler never called!
npm error This is an error with npm itself. Please report this error at:
npm error https://github.com/npm/cli/issues
npm error A complete log of this run can be found in: /.npm/_logs/2025-06-10T16_02_13_943Z-debug-0.log

✨ Finishing Touches
  • 📝 Generate Docstrings

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
🪧 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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 generate sequence diagram to generate a sequence diagram of the changes in 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

@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/interfaces/Thread.interface.ts (1)

46-46: Fix softDelete method return type to match async implementation.

The method signature should return Promise<void> since the schema implementation is async.

This issue was already flagged in the schema review. The interface should be updated to match the async implementation in the schema.

🧹 Nitpick comments (3)
.cursor/rules/mongo-lib.mdc (1)

1-11: Fix typos and clarify rule metadata
Resolve spelling errors, add meaningful glob patterns, and improve description clarity:

---
-description: 
-globs: 
-alwaysApply: true
+description: >
+  This project is a private npm package for interacting with MongoDB.
+globs:
+  - 'src/models/**/*.ts'
+  - 'src/repositories/**/*.ts'
+alwaysApply: true
---

- This Project is a private npm package. it's for all projects to interact with mongo db.
- Always use clean code and design patterns.
- Alwyas propose the codes base on the current strctour.
+ - This project is a private npm package for interacting with MongoDB.
+ - Always use clean code and design patterns.
+ - Always propose code based on the current structure.
src/models/schemas/Thread.schema.ts (1)

18-21: Consider using Date type for timestamp fields.

The archive_timestamp and create_timestamp fields are defined as String type, but they represent timestamps. Consider using Date type for better type safety and built-in date operations.

    archive_timestamp: {
-     type: String,
+     type: Date,
      required: true,
    },
    create_timestamp: {
-     type: String,
+     type: String,
      default: null,
    },

Also applies to: 31-34

src/interfaces/Thread.interface.ts (1)

49-51: Consider more specific typing for pagination method.

The paginate method could benefit from more specific type definitions instead of generic object and any types.

export interface ThreadModel extends Model<IThread, Record<string, unknown>, IThreadMethods> {
- paginate: (filter: object, options: object) => any;
+ paginate: (filter: FilterQuery<IThread>, options: PaginateOptions) => Promise<PaginateResult<IThread>>;
}

You'll need to import the appropriate types from your pagination plugin.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 2918635 and e064748.

📒 Files selected for processing (11)
  • .cursor/rules/mongo-lib.mdc (1 hunks)
  • CHANGELOG.md (0 hunks)
  • __tests__/unit/models/thread.model.test.ts (1 hunks)
  • src/interfaces/Thread.interface.ts (1 hunks)
  • src/interfaces/index.ts (1 hunks)
  • src/models/Thread.model.ts (1 hunks)
  • src/models/index.ts (2 hunks)
  • src/models/schemas/Channel.schema.ts (2 hunks)
  • src/models/schemas/Thread.schema.ts (1 hunks)
  • src/models/schemas/index.ts (2 hunks)
  • src/repositories/thread.repository.ts (1 hunks)
💤 Files with no reviewable changes (1)
  • CHANGELOG.md
🧰 Additional context used
🧬 Code Graph Analysis (3)
src/models/Thread.model.ts (1)
src/interfaces/Thread.interface.ts (2)
  • IThread (13-30)
  • ThreadModel (49-51)
__tests__/unit/models/thread.model.test.ts (2)
src/interfaces/Thread.interface.ts (1)
  • IThread (13-30)
src/models/index.ts (1)
  • Thread (28-28)
src/models/schemas/Thread.schema.ts (3)
src/models/schemas/index.ts (1)
  • threadSchema (29-29)
src/interfaces/Thread.interface.ts (2)
  • IThread (13-30)
  • ThreadModel (49-51)
src/models/schemas/plugins/index.ts (1)
  • toJSON (4-4)
🔇 Additional comments (11)
src/interfaces/index.ts (1)

14-14: Expose Thread interfaces in central index
You’ve correctly added the Thread.interface export to make all thread-related types available via the root interfaces module.

src/models/index.ts (2)

1-13: Integrate Thread model import and maintain alphabetical ordering
The Thread model import has been added and all model imports are now sorted alphabetically for consistency.


28-28: Export Thread model from index
Including Thread in the export block exposes it alongside other models in the central models index.

src/models/schemas/Channel.schema.ts (1)

22-22: Clean removal of redundant comment
Dropping the commented // id note streamlines the schema. The shorthand id: String remains clear and correct.

src/models/Thread.model.ts (1)

1-6: Register new Thread model
The Thread model is properly defined with model<IThread, ThreadModel>('Thread', threadSchema). Ensure threadSchema is exported in src/models/schemas/index.ts.

src/models/schemas/index.ts (1)

1-14: LGTM: Clean import organization and thread schema integration.

The import reordering improves code organization and the threadSchema is properly integrated following the existing pattern.

Also applies to: 29-29

src/repositories/thread.repository.ts (1)

1-13: LGTM: Well-structured repository implementation.

The repository follows established patterns with proper type safety and dependency injection. The factory function approach is consistent with the codebase architecture.

__tests__/unit/models/thread.model.test.ts (1)

1-96: LGTM: Comprehensive test coverage with proper validation scenarios.

The test suite effectively covers all validation rules, boundary conditions, and thread types. The test data aligns correctly with the schema constraints and uses appropriate async testing patterns.

src/models/schemas/Thread.schema.ts (2)

39-119: LGTM: Well-structured schema with comprehensive validation.

The schema provides thorough field validation, proper constraints, and follows Mongoose best practices with plugin integration and timestamps.

Also applies to: 127-128


16-16:

✅ Verification successful

Verify enum values align with Discord API specifications.

Ensure the auto_archive_duration values [60, 1440, 4320, 10080] and thread type values [10, 11, 12] match the current Discord API specifications for thread metadata and thread types.

Also applies to: 49-49


🌐 Web query:

What are the valid auto_archive_duration values and thread type values in the Discord API for thread entities?

💡 Result:

In the Discord API for thread entities, the valid values for auto_archive_duration and type (thread type) are as follows:

auto_archive_duration

The auto_archive_duration field specifies the duration in minutes after which a thread will automatically archive due to inactivity. Valid values are:

  • 60 (1 hour)
  • 1440 (24 hours / 1 day)
  • 4320 (3 days)
  • 10080 (7 days / 1 week)

Thread Type Values

The type field specifies the type of the thread. Valid thread types (represented as integers) are:

  • 10 - Public Thread
  • 11 - Private Thread
  • 12 - Announcement Thread (a thread created in an Announcement channel)

These values are aligned with the Discord API documentation as of now. If you want, I can also search for the latest official documentation to confirm if there have been any recent changes. Would you like me to do that?


All enum values match the current Discord API specifications—no changes required.

src/interfaces/Thread.interface.ts (1)

1-44: LGTM: Well-designed interfaces with proper type safety.

The interfaces provide comprehensive type definitions that align well with the schema structure. The use of Discord.js Snowflake type and optional/required field modifiers follows best practices.

@Behzad-rabiei Behzad-rabiei merged commit 43418bb into main Jun 10, 2025
3 checks passed
Copy link

@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 (1)
src/interfaces/Platfrom.interface.ts (1)

1-3: Consider the import style change implications.

The change from type-only imports (import { type Model, type Types }) to regular imports removes the explicit indication that these are used only for type annotations. Since Model and Types are only used in type positions (lines 7, 15, 24), type-only imports would typically be preferred for better tree-shaking and clearer intent.

However, if this is part of a broader standardization effort across the codebase, the consistency benefit may outweigh the type-only import advantages.

If not part of a deliberate pattern, consider reverting to type-only imports:

-import { Model, Types } from 'mongoose';
+import { type Model, type Types } from 'mongoose';
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between e064748 and 01a00ab.

📒 Files selected for processing (6)
  • src/interfaces/Announcement.interface.ts (2 hunks)
  • src/interfaces/Channel.interface.ts (1 hunks)
  • src/interfaces/GuildMember.interface.ts (1 hunks)
  • src/interfaces/Platfrom.interface.ts (1 hunks)
  • src/interfaces/Role.interface.ts (1 hunks)
  • src/interfaces/Thread.interface.ts (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • src/interfaces/Announcement.interface.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/interfaces/Thread.interface.ts
🔇 Additional comments (4)
src/interfaces/Platfrom.interface.ts (1)

5-26: Well-structured interface definitions.

The interface design is solid:

  • IPlatform captures all necessary platform properties including MongoDB ObjectId references
  • IPlatformUpdateBody appropriately makes all fields optional for partial updates
  • IPlatformMethods defines the async softDelete method correctly
  • PlatformModel properly extends Mongoose Model with pagination support

The use of Record<string, any> for metadata provides the needed flexibility for dynamic platform-specific data.

src/interfaces/Channel.interface.ts (1)

28-28:

❓ Verification inconclusive

Good change to make soft deletion asynchronous.

Converting the softDelete method to return Promise<void> aligns with the async nature of database operations and follows good patterns for soft deletion implementations.

Please verify that:

  1. The Channel schema/model implementation is updated to match this async interface
  2. All callers of this method are updated to handle the Promise
  3. Proper error handling is in place for the async operation

🏁 Script executed:

#!/bin/bash
# Description: Verify Channel softDelete implementation and usage
# Expected: Find async implementations and proper Promise handling

# Search for Channel softDelete implementations
echo "=== Channel softDelete implementations ==="
ast-grep --pattern $'softDelete() {
  $$$
}'

# Search for Channel softDelete method calls
echo "=== Channel softDelete method calls ==="
rg -A 3 -B 1 "\.softDelete\(\)" --type ts

Length of output: 696


Confirm Channel.softDelete implementation and callers

I didn’t find any async implementations or invocations of Channel.softDelete() in the codebase. Please verify that:

  • The Channel schema/model (e.g. src/models/channel.schema.ts) exports an async softDelete(): Promise<void> matching the updated interface.
  • All call sites of Channel.softDelete() use await or otherwise handle the returned Promise<void>.
  • Adequate error handling (e.g. try/catch) is in place for this async operation.
src/interfaces/Role.interface.ts (1)

18-18:

✅ Verification successful

Consistent async pattern for soft deletion.

The change to make softDelete return Promise<void> maintains consistency with other entity interfaces and properly reflects the asynchronous nature of database operations.

Ensure the Role schema implementation and all callers are updated to handle the async method signature.


🏁 Script executed:

#!/bin/bash
# Description: Verify Role softDelete implementation consistency
# Expected: Find matching async implementations

# Search for Role schema softDelete implementations
echo "=== Role softDelete implementations ==="
ast-grep --pattern $'softDelete() {
  $$$
}' --lang typescript

# Check for any remaining synchronous softDelete calls
echo "=== Role softDelete usage patterns ==="
rg -A 2 "role.*\.softDelete\(\)" --type ts

Length of output: 598


To get a complete picture of where and how softDelete is defined and used, let’s search the entire codebase for every occurrence:


🏁 Script executed:

#!/bin/bash
# Description: Locate all definitions and usages of `softDelete` in .ts files

echo "=== All occurrences of softDelete in TypeScript files ==="
rg --color=never -n "softDelete" --glob "*.ts"

echo
echo "=== async softDelete definitions ==="
rg --color=never -n "async softDelete" --glob "*.ts"

Length of output: 1673


Confirmed async softDelete consistency

All entity schemas—including Role.schema.ts at line 22—define softDelete as an async method, matching the updated interface signature (() => Promise<void>). No remaining synchronous .softDelete() calls were found.

src/interfaces/GuildMember.interface.ts (1)

50-50:

✅ Verification successful

Completes the async soft deletion standardization.

This change to Promise<void> completes the consistent async pattern for soft deletion across Channel, Role, and GuildMember interfaces, aligning with the Thread entity introduction mentioned in the PR objectives.

Verify that the GuildMember implementation matches and that this completes the async soft deletion standardization across all entity types.


🏁 Script executed:

#!/bin/bash
# Description: Verify GuildMember softDelete and overall consistency
# Expected: Find consistent async implementations across all entities

# Search for all softDelete method implementations
echo "=== All softDelete implementations ==="
ast-grep --pattern $'softDelete() {
  $$$
}' --lang typescript

# Verify all softDelete interfaces are now async
echo "=== All softDelete interface declarations ==="
rg "softDelete.*Promise<void>" --type ts

# Check for any remaining sync softDelete declarations
echo "=== Any remaining sync softDelete declarations ==="
rg "softDelete.*\(\).*void[^>]" --type ts

Length of output: 1119


🏁 Script executed:

#!/bin/bash
# Verify that async softDelete implementations exist in code (not just interfaces)

echo "=== async softDelete implementations ==="
rg -n "^\s*async\s+softDelete" --type ts

echo "=== softDelete methods outside interface files ==="
rg -n "softDelete\s*\(" --type ts | grep -v "interface.ts"

Length of output: 1052


Approve async soft deletion standardization completion

All softDelete methods in the TypeScript interfaces have been updated to return Promise<void> (Thread.interface.ts, Channel.interface.ts, Role.interface.ts, Platform.interface.ts, GuildMember.interface.ts), and each corresponding Mongoose schema registers an async function softDelete(...) implementation (models/schemas/*.schema.ts). No remaining synchronous declarations were found.

– Interfaces: softDelete: () => Promise<void>;
– Implementations: schema.method('softDelete', async function softDelete() { … })

No further action required.

@@ -1,5 +1,6 @@
import { type Model, type Types } from 'mongoose';
import { type PlatformNames } from '../config/enums';
import { Model, Types } from 'mongoose';
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix the filename typo.

The filename contains a typo: "Platfrom" should be "Platform". This could cause confusion and make the file harder to find.

Consider renaming the file to Platform.interface.ts to correct the typo.

🤖 Prompt for AI Agents
In src/interfaces/Platfrom.interface.ts at line 1, the filename contains a typo
"Platfrom" instead of "Platform". Rename the file from Platfrom.interface.ts to
Platform.interface.ts to correct the spelling and avoid confusion.

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.

1 participant