Skip to content
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

Add JSDoc to pagination code #762

Merged
merged 5 commits into from
Jan 10, 2025
Merged

Add JSDoc to pagination code #762

merged 5 commits into from
Jan 10, 2025

Conversation

rosado
Copy link
Collaborator

@rosado rosado commented Jan 6, 2025

What type of PR is this? (check all applicable)

  • Refactor
  • Documentation Update

Description

This PR adds some JSDoc comments and to make it easier to spot errors in the pagination code.

Related Tickets & Documents

None

Added/updated tests?

  • No, and this is why: No functionality changed and code is already covered by unit tests.

QA sign off

  • Code has been checked and approved
  • Design has been checked and approved no design changes
  • Product and business logic has been checked and proved no logic changes

Summary by CodeRabbit

Release Notes

  • Documentation

    • Added comprehensive JSDoc comments to improve code documentation and type clarity.
    • Enhanced function and method descriptions across multiple utility files.
  • Improvements

    • Updated type annotations for better type safety.
    • Refined pagination object initialisation to prevent potential runtime errors.
    • Improved error handling and logging mechanisms.
  • New Features

    • Introduced a configuration validation function.

These updates focus on enhancing code reliability, type safety, and documentation without introducing significant user-facing changes.

@rosado rosado requested a review from DilwoarH January 6, 2025 12:07
Copy link
Contributor

coderabbitai bot commented Jan 6, 2025

Walkthrough

The pull request introduces improvements to configuration validation, middleware type safety, and documentation across multiple files. The changes focus on enhancing type annotations, initialising variables more robustly, and adding comprehensive JSDoc comments. The modifications aim to improve code clarity, prevent potential runtime errors, and provide better type checking for various utility functions and middleware components.

Changes

File Change Summary
config/util.js Added validateConfig function with schema validation and error handling.
src/middleware/common.middleware.js - Updated logPageError parameter type annotation.
- Modified paginationObj.items initialisation.
- Changed item population method from map to for...of loop.
- Added JSDoc type definition for paginationObj.
src/utils/pagination.js Added JSDoc comment block for pagination function.

Possibly related PRs

  • Add issue table view #691: The main PR introduces a new function validateConfig in config/util.js, which validates configuration objects, while PR Add issue table view #691 involves enhancements to the issue table view, including pagination and structured data handling. Both PRs focus on improving data management and validation, indicating a potential relationship in how configurations might affect the new issue table's functionality.

Suggested reviewers

  • DilwoarH

Poem

🐰 Validation's dance, types so bright,
Code refactored with rabbit delight!
Middleware singing, errors take flight,
Documentation shining clear and tight,
A symphony of code, pure and right! 🔍


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between f3efb6b and 02c1d8d.

📒 Files selected for processing (1)
  • src/middleware/common.middleware.js (5 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/middleware/common.middleware.js
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: run-tests / test

Finishing Touches

  • 📝 Generate Docstrings

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ 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.
    • 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. (Beta)
  • @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.

This comment was marked as resolved.

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 (4)
src/utils/pagination.js (1)

4-10: Add a short function description.

While the parameter annotations are helpful, it would be clearer to include a high-level summary of what this function does. This helps maintainers and third-party developers quickly understand its purpose.

 /**
+ * Creates an array of pages or ellipse placeholders for pagination controls.
  * @param {number} count
  * @param {number} current
  * @param {string} ellipsis
  * @returns {(number | string)[]}
  */
config/util.js (1)

118-124: Mention logging side effects in the doc comment.

The JSDoc is clear about what happens if validation fails, but it might be helpful to mention that errors are also logged prior to rethrowing them. This documents the side effects for maintainers.

 /**
  * Validates the config object against the ConfigSchema.
  *
  * @param {*} config
  * @returns {v.InferOutput<typeof ConfigSchema>}
  * @throws {v.ValibotError} - Logs validation errors and rethrows.
  */
src/middleware/common.middleware.js (2)

130-130: Use a structured or custom error type instead of @ts-ignore.

Using @ts-ignore here can hide potential type mismatches. Consider extending the error class or using a typed error interface to avoid ignoring type checks.

- // @ts-ignore
  error.status = 404
+ (error as CustomError).status = 404

170-186: Consider removing the 'unexpected pagination item' warning or handling other cases.

The loop currently covers '...' and numeric items. If you anticipate other item types, handle them explicitly; otherwise, this warning might create noise in logs.

  for (const item of pagination(dataRange.maxPageNumber, Math.min(pageNumber, dataRange.maxPageNumber))) {
    if (item === '...') {
      ...
    } else if (typeof item === 'number') {
      ...
    }
-   logger.warn('unexpected pagination item', { item, dataRange, types: types.App, endpoint: req.originalUrl })
+   // No further cases expected, consider removing or refactoring.
  }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 38a5175 and 2632d08.

📒 Files selected for processing (3)
  • config/util.js (1 hunks)
  • src/middleware/common.middleware.js (5 hunks)
  • src/utils/pagination.js (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: run-tests / test
🔇 Additional comments (3)
src/middleware/common.middleware.js (3)

15-15: Ensure consistent request typing.

Specifying req as import('express').Request & { handlerName: string } is a solid enhancement for type safety. Confirm that this updated type is consistent with all middlewares and routes that use the req.handlerName property.


150-152: Appreciate the new JSDoc type definition.

Defining a clear shape for paginationObj promotes maintainability and makes this code more self-documenting.


156-156: Excellent choice to initialise items as an empty array.

This eliminates the risk of runtime errors when pushing to paginationObj.items. Good work.

} else {
return {
})
} else if (typeof item === 'number') {
Copy link
Contributor

Choose a reason for hiding this comment

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

What will happen if it's not a number? The original code suggests that the item was a string?

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

The not a number case is the ellipsis string ('...'), handled in the first branch. But now that I look at it, the warning should be in an 'else'. Updated that.

@rosado rosado mentioned this pull request Jan 9, 2025
5 tasks
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/middleware/common.middleware.js (2)

130-132: Consider using a custom error class instead of @ts-ignore

Rather than suppressing TypeScript errors, consider creating a custom error class that includes the status property. This would provide better type safety and maintainability.

+class HttpError extends Error {
+  constructor(message: string, status: number) {
+    super(message);
+    this.status = status;
+  }
+  status: number;
+}

-const error = new Error('page number not in range')
-// @ts-ignore
-error.status = 404
+const error = new HttpError('page number not in range', 404)

170-187: Enhance error logging for unexpected pagination items

The type checking is good, but the error logging could be more descriptive to aid debugging.

-      logger.warn('unexpected pagination item', { item, dataRange, types: types.App, endpoint: req.originalUrl })
+      logger.warn('unexpected pagination item type', {
+        item,
+        itemType: typeof item,
+        dataRange,
+        types: types.App,
+        endpoint: req.originalUrl
+      })
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 2632d08 and f3efb6b.

📒 Files selected for processing (1)
  • src/middleware/common.middleware.js (5 hunks)
🔇 Additional comments (2)
src/middleware/common.middleware.js (2)

15-15: Well-structured type annotation!

The type annotation for the req parameter enhances type safety by explicitly defining the expected structure.


150-156: Excellent type definition and initialization!

The JSDoc type definition clearly documents the pagination object structure, and initializing items as an empty array prevents potential runtime errors.

@eveleighoj eveleighoj temporarily deployed to submit-pr-762 January 9, 2025 16:36 Inactive
@rosado rosado merged commit 9d7c5c0 into main Jan 10, 2025
5 checks passed
@rosado rosado deleted the rosado/NOTICKET-docs-tweaks branch January 10, 2025 16:44
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.

3 participants