Skip to content

feat: enhance hasUserVoted query to include hasVoted #3451

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 12 commits into from
Apr 13, 2025

Conversation

im-vedant
Copy link

@im-vedant im-vedant commented Apr 13, 2025

What kind of change does this PR introduce?

Issue Number:

Fixes #3426

Snapshots/Videos:

If relevant, did you update the documentation?

Summary

Does this PR introduce a breaking change?

Checklist

CodeRabbit AI Review

  • I have reviewed and addressed all critical issues flagged by CodeRabbit AI
  • I have implemented or provided justification for each non-critical suggestion
  • I have documented my reasoning in the PR comments where CodeRabbit AI suggestions were not implemented

Test Coverage

  • I have written tests for all new changes/features
  • I have verified that test coverage meets or exceeds 95%
  • I have run the test suite locally and all tests pass

Other information

Have you read the contributing guide?

Summary by CodeRabbit

Summary by CodeRabbit

  • New Features

    • The voting status indicator now clearly shows whether you have voted.
    • Pledge queries have been enhanced with pagination controls and additional sorting and filtering options.
  • Tests

    • Expanded test coverage ensures reliable display of vote status in different user scenarios, including scenarios where users have and have not voted.
    • New tests validate error handling for invalid inputs and resource existence.

Copy link

coderabbitai bot commented Apr 13, 2025

Walkthrough

This pull request updates the GraphQL schema and associated resolvers for the HasUserVoted type and pledge queries. The changes introduce a new hasVoted field (of type Boolean!) while making the type field nullable. In addition, the getPledgesByUserId query now accepts limit and offset parameters. The PR also reintroduces the QueryPledgeOrderByInput enum and QueryPledgeWhereInput input type, with corresponding updates in resolver logic and tests to improve vote-checking functionality.

Changes

File(s) Summary
schema.graphql Updated the HasUserVoted type (added hasVoted: Boolean! and made type nullable), added limit/offset to getPledgesByUserId, and reintroduced pledge query inputs.
src/graphql/types/…/hasUserVoted.ts, src/graphql/types/Query/hasUserVoted.ts Modified resolver logic for HasUserVoted: renamed variables, updated error handling, and integrated the new hasVoted field with an updated vote-checking flow.
test/graphql/types/Query/hasUserVoted.test.ts, test/graphql/types/documentNodes.ts Adjusted tests to cover the new hasVoted field behavior, verifying responses for both voted and not-voted cases and updating the query document structure.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Resolver as "hasUserVoted Resolver"
    participant DB as "Database"
    
    User->>Resolver: Query hasUserVoted
    Resolver->>DB: Fetch post and organization membership
    DB-->>Resolver: Return post and membership details
    Resolver->>DB: Check for user's vote on post
    DB-->>Resolver: Return vote info or null
    Resolver-->>User: Respond with { hasVoted, type }
Loading

Assessment against linked issues

Objective Addressed Explanation
Add hasUserVoted query to determine if a user has upvoted, downvoted, or not voted on a post (#3426)

Suggested labels

ignore-sensitive-files-pr

Suggested reviewers

  • gautam-divyanshu
  • palisadoes

Tip

⚡💬 Agentic Chat (Pro Plan, General Availability)
  • We're introducing multi-step agentic chat in review comments and issue comments, within and outside of PR's. This feature enhances review and issue discussions with the CodeRabbit agentic chat by enabling advanced interactions, including the ability to create pull requests directly from comments and add commits to existing pull requests.

📜 Recent review details

Configuration used: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 7f3edd2 and eecbfdd.

📒 Files selected for processing (1)
  • test/graphql/types/Query/hasUserVoted.test.ts (4 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
test/graphql/types/Query/hasUserVoted.test.ts (2)
test/graphql/types/client.ts (1)
  • mercuriusClient (7-9)
test/graphql/types/documentNodes.ts (1)
  • Query_hasUserVoted (1056-1064)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Run tests for talawa api
  • GitHub Check: Analyse Code With CodeQL (typescript)
🔇 Additional comments (4)
test/graphql/types/Query/hasUserVoted.test.ts (4)

224-245: Well-structured input validation tests!

This new test suite correctly validates that the system rejects invalid UUIDs with the proper error code. The test now uses proper authentication with the admin token and expects the more appropriate "invalid_arguments" error code.


246-267: Good separation of resource existence checks

Excellent restructuring to separate resource existence tests from input validation. Using a valid but non-existent UUID is a better approach than an invalid format, and the expected error code is appropriate for this scenario.


302-324: Correctly implements the "user has not voted" scenario

This test properly addresses the core functionality described in the PR objectives. It correctly tests that when a user hasn't voted on a post:

  1. The response is not null and contains no errors
  2. The voteType is null
  3. The new hasVoted field is false

This resolves the issue mentioned in the previous review comment where the test setup was contradictory.


357-360: Updated assertions align with schema changes

These updated assertions correctly check the new field names and values:

  • Using voteType instead of type
  • Verifying that hasVoted is true when a user has voted

This ensures the test properly validates the enhanced schema.

✨ 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 plan to trigger planning for file edits and PR creation.
  • @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.

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

Our Pull Request Approval Process

Thanks for contributing!

Testing Your Code

Remember, your PRs won't be reviewed until these criteria are met:

  1. We don't merge PRs with poor code quality.
    1. Follow coding best practices such that CodeRabbit.ai approves your PR.
  2. We don't merge PRs with failed tests.
    1. When tests fail, click on the Details link to learn more.
    2. Write sufficient tests for your changes (CodeCov Patch Test). Your testing level must be better than the target threshold of the repository
    3. Tests may fail if you edit sensitive files. Ask to add the ignore-sensitive-files-pr label if the edits are necessary.
  3. We cannot merge PRs with conflicting files. These must be fixed.

Our policies make our code better.

Reviewers

Do not assign reviewers. Our Queue Monitors will review your PR and assign them.
When your PR has been assigned reviewers contact them to get your code reviewed and approved via:

  1. comments in this PR or
  2. our slack channel

Reviewing Your Code

Your reviewer(s) will have the following roles:

  1. arbitrators of future discussions with other contributors about the validity of your changes
  2. point of contact for evaluating the validity of your work
  3. person who verifies matching issues by others that should be closed.
  4. person who gives general guidance in fixing your tests

CONTRIBUTING.md

Read our CONTRIBUTING.md file. Most importantly:

  1. PRs with issues not assigned to you will be closed by the reviewer
  2. Fix the first comment in the PR so that each issue listed automatically closes

Other

  1. 🎯 Please be considerate of our volunteers' time. Contacting the person who assigned the reviewers is not advised unless they ask for your input. Do not @ the person who did the assignment otherwise.
  2. Read the CONTRIBUTING.md file make

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

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 241112d and 840ca60.

📒 Files selected for processing (5)
  • schema.graphql (3 hunks)
  • src/graphql/types/Post/hasUserVoted.ts (1 hunks)
  • src/graphql/types/Query/hasUserVoted.ts (4 hunks)
  • test/graphql/types/Query/hasUserVoted.test.ts (2 hunks)
  • test/graphql/types/documentNodes.ts (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (2)
test/graphql/types/Query/hasUserVoted.test.ts (2)
test/graphql/types/client.ts (1)
  • mercuriusClient (7-9)
test/graphql/types/documentNodes.ts (2)
  • Mutation_createPostVote (1066-1072)
  • Query_hasUserVoted (1056-1064)
src/graphql/types/Post/hasUserVoted.ts (3)
src/graphql/builder.ts (1)
  • builder (10-20)
src/drizzle/enums/postVoteType.ts (1)
  • postVoteTypeEnum (6-6)
src/graphql/enums/PostVoteType.ts (1)
  • PostVoteType (4-7)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Run tests for talawa api
  • GitHub Check: Analyse Code With CodeQL (typescript)
🔇 Additional comments (7)
test/graphql/types/documentNodes.ts (1)

1061-1061: GraphQL query updated correctly to include hasVoted field

The Query_hasUserVoted query has been enhanced to include the new hasVoted field, which properly aligns with the updated schema. This change ensures that clients can now check not only the vote type but also explicitly whether a user has voted.

src/graphql/types/Post/hasUserVoted.ts (3)

7-8: Good addition of hasVoted field and nullable type

The object reference has been correctly updated to include the new hasVoted boolean field while making the type field nullable. This change enhances the API by providing more explicit information about the voting status.


13-18: Well-implemented field definition for hasVoted

The implementation for the hasVoted field looks good. It's properly typed as a non-nullable Boolean with an appropriate description and resolver.


21-22: Clear documentation for nullable type field

The nullable flag and updated description clearly communicate that the type field can be null when no vote exists, which improves API understanding for consumers.

test/graphql/types/Query/hasUserVoted.test.ts (1)

375-375: Good assertion for hasVoted field

The addition of this assertion correctly verifies that hasVoted is true when a user has actually voted, which complements the test for the case when a user has not voted.

schema.graphql (2)

3371-3377: New Pagination Parameters for getPledgesByUserId Query

The addition of the optional limit: Int and offset: Int parameters allows callers to control pagination effectively. Please verify that the corresponding resolver logic correctly handles cases where these parameters are omitted (e.g. defaulting to return all results or applying implicit limits).


3534-3552: Addition of Sorting and Filtering for Pledge Queries

The reintroduction of the QueryPledgeOrderByInput enum—offering values like amount_ASC, amount_DESC, endDate_ASC, and endDate_DESC—and the new QueryPledgeWhereInput (which enables filtering by the creator's first name and campaign name) enhance query flexibility. Make sure the resolver logic is updated to interpret these new inputs appropriately.

@im-vedant im-vedant changed the title Fix bug feat: enhance hasUserVoted query to include hasVoted Apr 13, 2025
Copy link

codecov bot commented Apr 13, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 59.07%. Comparing base (241112d) to head (eecbfdd).
Report is 2 commits behind head on develop-postgres.

Additional details and impacted files
@@                 Coverage Diff                  @@
##           develop-postgres    #3451      +/-   ##
====================================================
+ Coverage             59.06%   59.07%   +0.01%     
====================================================
  Files                   523      523              
  Lines                 40662    40674      +12     
  Branches               1732     1735       +3     
====================================================
+ Hits                  24018    24030      +12     
  Misses                16635    16635              
  Partials                  9        9              

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

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

♻️ Duplicate comments (1)
schema.graphql (1)

776-782: Enhanced HasUserVoted Type Definition

The updated HasUserVoted type now clearly exposes a non-nullable hasVoted: Boolean! field and renames the previous type field to voteType, which is now nullable. This change improves clarity and better represents the possibility that no vote exists. Please ensure that all client-side queries and resolver implementations are updated accordingly.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 8ed12aa and 7f3edd2.

📒 Files selected for processing (5)
  • schema.graphql (3 hunks)
  • src/graphql/types/Post/hasUserVoted.ts (1 hunks)
  • src/graphql/types/Query/hasUserVoted.ts (3 hunks)
  • test/graphql/types/Query/hasUserVoted.test.ts (2 hunks)
  • test/graphql/types/documentNodes.ts (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (3)
src/graphql/types/Post/hasUserVoted.ts (3)
src/graphql/builder.ts (1)
  • builder (10-20)
src/drizzle/enums/postVoteType.ts (1)
  • postVoteTypeEnum (6-6)
src/graphql/enums/PostVoteType.ts (1)
  • PostVoteType (4-7)
src/graphql/types/Query/hasUserVoted.ts (1)
src/utilities/TalawaGraphQLError.ts (1)
  • TalawaGraphQLError (264-277)
test/graphql/types/Query/hasUserVoted.test.ts (2)
test/graphql/types/client.ts (1)
  • mercuriusClient (7-9)
test/graphql/types/documentNodes.ts (1)
  • Query_hasUserVoted (1056-1064)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Run tests for talawa api
🔇 Additional comments (16)
test/graphql/types/documentNodes.ts (1)

1060-1061: Good alignment with the updated schema.

Adding voteType and hasVoted to the returned fields properly matches the changes introduced in the HasUserVoted object and ensures the query accurately reflects a user's voting status.

src/graphql/types/Post/hasUserVoted.ts (5)

5-5: No content change for this line.

It appears to be a placeholder or formatting adjustment rather than a functional modification. No issue here.


7-8: Schema fields introduced successfully.

Defining hasVoted and voteType at the objectRef level clarifies the data shape for the HasUserVoted object, aligning with the new schema requirements.


13-14: Field definition reflects intended behavior.

Using "Boolean" as a non-nullable type for hasVoted helps ensure consistent data usage in clients that consume this API.


16-17: Proper resolver usage.

Resolving hasVoted directly from the parent object is straightforward and adheres to GraphQL best practices.


19-22: Handling nullability with clarity.

Exposing voteType as a nullable field makes sense given that a user might not have voted at all, so null is a valid state.

test/graphql/types/Query/hasUserVoted.test.ts (2)

281-303: Test coverage improvement.

Verifying that voteType is null and hasVoted is false accurately covers the scenario where no vote record exists, ensuring correctness of the field behaviors.


336-339: Correct assertions for voted scenario.

Checking both voteType and hasVoted ensures the query response is consistent when a vote does exist. This thoroughly tests the new schema fields.

src/graphql/types/Query/hasUserVoted.ts (6)

53-54: Parallel queries for efficiency.

Using Promise.all to retrieve user, post, and vote data concurrently optimizes wait time and improves performance. Well done.


55-89: Comprehensive data retrieval in one pass.

Fetching user data, post details (including organization and membership), and existing votes in a single set of queries is consistent and maintains clarity in logic. Just ensure the nested relationships remain efficient for large datasets.


97-97: Clear error handling for missing post.

Throwing an arguments_associated_resources_not_found error if the post is absent properly aligns with typical GraphQL error patterns.


109-110: Potential edge case with multiple memberships.

Accessing the first element ([0]) in membershipsWhereOrganization is fine if there is only a single membership. However, if a user can have multiple memberships or roles for the same organization, consider verifying that [0] is the intended membership or handle multiple entries if needed.


124-129: Graceful handling of no-vote scenario.

Returning an object with voteType: null and hasVoted: false nicely captures the case when a user has not voted. This approach is consistent with the new schema contract.


131-132: Returning valid vote status.

Ensuring voteType and hasVoted are set correctly when a vote exists completes the logic for both voting states, aligning perfectly with the schema updates.

schema.graphql (2)

3534-3542: New Sorting Enum: QueryPledgeOrderByInput

The newly introduced QueryPledgeOrderByInput enum (with values such as amount_ASC, amount_DESC, endDate_ASC, and endDate_DESC) standardizes the sorting criteria used in pledge queries. Ensure that the resolver correctly interprets these enum values so that sorted results are returned as expected.


3544-3551: New Filter Input: QueryPledgeWhereInput

The QueryPledgeWhereInput input type now facilitates filtering pledges by fields like the creator’s first name and the campaign name. This added flexibility is beneficial for more granular queries. You might consider adding additional documentation or even examples (if not already provided elsewhere) on how these filters combine when multiple criteria are passed.

coderabbitai[bot]
coderabbitai bot previously approved these changes Apr 13, 2025
@im-vedant
Copy link
Author

@palisadoes This PR extends a previously closed issue. Earlier, an error was thrown when a user had not voted on a post. Now, this case is handled gracefully by introducing a hasVoted variable, which indicates whether the user has voted on the post. If the user has voted, the voteType (i.e., upvote or downvote) is also included in the response. This PR is ready to be merged.

@palisadoes palisadoes merged commit 3ee59b7 into PalisadoesFoundation:develop-postgres Apr 13, 2025
18 of 19 checks passed
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.

2 participants