Skip to content

fix (advertisements): fetch advertisements correctly with their completion status in infinite scroll #3444

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

Conversation

bandhan-majumder
Copy link

@bandhan-majumder bandhan-majumder commented Apr 11, 2025

What kind of change does this PR introduce?

feature

Issue Number:

Fixes #3443

Snapshots/Videos:

N/A

If relevant, did you update the documentation?

N/A

Summary

Allows advertisements to be fetched with completion status

Does this PR introduce a breaking change?

N/A

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

This is needed for the frontend issue PalisadoesFoundation/talawa-admin#3557

Have you read the contributing guide?

Summary by CodeRabbit

  • New Features
    • Introduced an enhanced filtering option for advertisements. Users can now specify the completion status when querying advertisements, allowing for more precise results and improved data retrieval efficiency.
    • Added new GraphQL queries and mutations for fetching and creating advertisements related to an organization.
  • Bug Fixes
    • Improved error handling for unauthenticated access to advertisement queries.
  • Tests
    • Implemented a new test suite for validating advertisement-related functionalities, including unauthenticated access, response structure, and pagination.

Copy link

coderabbitai bot commented Apr 11, 2025

Walkthrough

This pull request introduces a new input type, AdvertisementWhereInput, featuring a boolean field isCompleted to filter advertisements by completion status. The changes update the GraphQL schema by modifying the advertisements field in the Organization type to accept this new filter. Additionally, argument transformation logic in the advertisement resolver is refactored to process the new filtering mechanism. Test definitions are also updated to include the new input type.

Changes

File(s) Change Summary
schema.graphql, src/graphql/inputs/QueryOrganizationInput.ts, test/graphql/types/gql.tada.d.ts Added new input type AdvertisementWhereInput with the isCompleted field to support advertisement filtering.
src/graphql/types/Organization/advertisements.ts Updated the advertisements field to include a where argument and integrated filtering logic using createGraphQLConnectionWithWhereSchema.
test/routes/graphql/documentNodes.ts Introduced new GraphQL queries and mutations: Query_advertisements and Mutation_createAdvertisement.
test/graphql/types/Organization/advertisement.test.ts Added a new test suite to validate the behavior of advertisements filtering and pagination in the GraphQL API.

Sequence Diagram(s)

sequenceDiagram
    participant C as Client
    participant G as GraphQL Server
    participant R as Advertisement Resolver
    participant D as Database

    C->>G: Query advertisements(where: { isCompleted: true/false })
    G->>R: Forward query with pagination and where arguments
    R->>R: Process args with createGraphQLConnectionWithWhereSchema
    R->>D: Query database with filtered criteria
    D-->>R: Return filtered advertisements
    R-->>G: Deliver results
    G-->>C: Send response
Loading

Assessment against linked issues

Objective Addressed Explanation
Filter advertisements based on completion status (#3443)

📜 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 e9342f5 and 5cb1b33.

📒 Files selected for processing (1)
  • test/graphql/types/Organization/advertisement.test.ts (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
test/graphql/types/Organization/advertisement.test.ts (3)
test/graphql/types/client.ts (1)
  • mercuriusClient (7-9)
test/routes/graphql/documentNodes.ts (4)
  • Mutation_createOrganization (370-377)
  • Query_signIn (191-218)
  • Query_advertisements (721-765)
  • Mutation_createAdvertisement (767-773)
test/server.ts (1)
  • server (12-27)
⏰ 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 (5)
test/graphql/types/Organization/advertisement.test.ts (5)

1-47: Looking good: Suite name matches functionality being tested.

The updated test suite name now reflects that we're testing advertisements with completion status, which addresses the previous review comment about the suite name not matching the tested functionality.


260-312: Well implemented: Comprehensive test for unfiltered advertisements.

This test correctly verifies that when isCompleted filter is not specified (using where: null), both active and completed advertisements are returned. This ensures backward compatibility and validates the new filtering mechanism.


608-662: Well-structured: Comprehensive field validation for advertisement nodes.

This test thoroughly validates all the expected fields in the advertisement data structure, ensuring the API returns the correct advertisement information when queried with the completion status filter.


416-497: Good implementation: Cursor-based pagination with completion status filtering.

The test for pagination using the 'after' parameter correctly verifies that subsequent pages contain different advertisements than the first page while maintaining the completion status filtering. This ensures that the pagination mechanism works properly with the new filtering feature.


498-606: Well handled: Graceful error handling for invalid pagination parameters.

These tests verify that the API handles invalid pagination parameters appropriately, providing clear error messages and codes. This is essential for robust API design and good user experience.

✨ 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

coderabbitai[bot]
coderabbitai bot previously approved these changes Apr 11, 2025
@Cioppolo14
Copy link
Contributor

There isn’t an issue assigned to you for this PR. Please follow the guidelines in our PR_GUIDELINES.md file. We have the procedures in place so that everyone has a fair chance of contributing. I will be closing this pull request. Please follow the procedures and resubmit when ready.

@Cioppolo14 Cioppolo14 closed this Apr 11, 2025
@bandhan-majumder bandhan-majumder changed the title Bandhan majumder/feat ads 1 fix(infinite scroll advertisements): fetch advertisements correctly with their completion status Apr 11, 2025
@bandhan-majumder bandhan-majumder changed the title fix(infinite scroll advertisements): fetch advertisements correctly with their completion status fix (advertisements): fetch advertisements correctly with their completion status in infinite scroll Apr 11, 2025
@bandhan-majumder
Copy link
Author

bandhan-majumder commented Apr 12, 2025

@Cioppolo14 @palisadoes can this pr be opened now?

@palisadoes palisadoes reopened this Apr 12, 2025
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

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 0195768 and 3e45a78.

📒 Files selected for processing (2)
  • schema.graphql (3 hunks)
  • test/graphql/types/gql.tada.d.ts (1 hunks)
⏰ 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 (1)
test/graphql/types/gql.tada.d.ts (1)

265-266: File formatting improvement.

Adding a newline at the end of the file is a good practice and adheres to common coding standards. This change has no functional impact but improves consistency in the codebase.

coderabbitai[bot]
coderabbitai bot previously approved these changes Apr 13, 2025
@palisadoes
Copy link
Contributor

  1. Please make coderabbit.ai approves your work.
  2. Resolve any conflicting files
  3. Make sure all tests pass and are valid.
  4. Ensure the test code coverage for your patch reaches as close to 100% as possible.

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

🔭 Outside diff range comments (1)
test/routes/graphql/documentNodes.ts (1)

1-773: 💡 Verification agent

🧩 Analysis chain

Fix the formatting issues identified by the pipeline.

The GitHub Actions workflow has identified formatting issues in the code. While the indentation changes are an improvement, there are still formatting issues that need to be addressed.


🏁 Script executed:

#!/bin/bash
# Find the formatter used in the project and see if there are config files
echo "Checking for formatter configuration files:"
find . -maxdepth 2 -name "*.prettier*" -o -name "*.eslint*" -o -name "*.format*"

# Check package.json for formatting scripts
echo -e "\nChecking package.json for formatting scripts:"
grep -A 3 '"format"' package.json || echo "No format script found"

# Try to find documentation about formatting
echo -e "\nChecking for documentation about formatting:"
find . -maxdepth 2 -name "CONTRIBUTING.md" | xargs grep -l "format" || echo "No formatting documentation found"

Length of output: 625


Action Required: Address Formatting Issues in test/routes/graphql/documentNodes.ts

The GitHub Actions workflow still flags formatting problems in this file. Although the indentation changes are an improvement, our verification shows that the project currently lacks any formatter configuration (no Prettier, ESLint, or custom formatting scripts in package.json, nor documentation in CONTRIBUTING.md). Please add the appropriate formatter configuration or manually reformat the code to adhere to our style guidelines.

🧰 Tools
🪛 GitHub Actions: Pull request workflow

[error] 6-684: Formatter would have printed the following content indicating formatting issues. Please run the formatter to fix the code style.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 3e45a78 and ecca390.

📒 Files selected for processing (1)
  • test/routes/graphql/documentNodes.ts (18 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
test/routes/graphql/documentNodes.ts (2)
test/routes/graphql/gql.tada.d.ts (1)
  • introspection (6710-6716)
src/graphql/scalars/index.ts (1)
  • ClientCustomScalars (30-36)
🪛 GitHub Actions: Pull request workflow
test/routes/graphql/documentNodes.ts

[error] 6-684: Formatter would have printed the following content indicating formatting issues. Please run the formatter to fix the code style.

⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Analyse Code With CodeQL (typescript)
🔇 Additional comments (6)
test/routes/graphql/documentNodes.ts (6)

8-9: Formatting improvement looks good.

The indentation changes make the code more consistent and readable.


13-40: Consistent indentation applied throughout document nodes.

The formatting changes across all these GraphQL document nodes improve code readability while maintaining functionality. This is a good practice for maintaining a consistent code style.

Also applies to: 43-47, 50-74, 77-104, 107-131, 134-158, 187-189, 298-324, 327-331, 334-360, 371-377, 380-386, 389-393, 396-402, 405-411, 414-420, 450-467, 470-474, 477-490, 573-582, 677-679, 682-684


721-765: Great implementation of the query for fetching advertisements with filtering.

This new Query_advertisements GraphQL query includes:

  1. The required organization ID parameter
  2. Standard pagination parameters (first, last, after, before)
  3. The new filtering parameter using AdvertisementWhereInput which supports the isCompleted field
  4. A comprehensive response structure with all necessary advertisement fields
  5. Proper pagination metadata

This implementation effectively supports the PR objective of fetching advertisements with their completion status in infinite scroll.


767-773: Simple and effective mutation for creating advertisements.

The Mutation_createAdvertisement follows the established pattern in this codebase for mutation definitions. It provides the minimum required feedback (the ID of the created advertisement) which is sufficient for most client-side use cases.


728-729:

✅ Verification successful

Ensure the AdvertisementWhereInput type is properly defined in the schema.

The query uses AdvertisementWhereInput as a filter parameter, which should include the isCompleted boolean field mentioned in the PR description. Make sure this type is properly defined in the schema file.


🏁 Script executed:

#!/bin/bash
# Check if the AdvertisementWhereInput type exists in the schema
echo "Checking for AdvertisementWhereInput in schema files:"
find . -name "*.graphql" | xargs grep -l "AdvertisementWhereInput" | while read file; do
  echo "Found in $file:"
  cat "$file" | grep -A 10 "AdvertisementWhereInput" || echo "Not found in expected format"
done

# Check if there are resolver implementations for this input type
echo -e "\nChecking for resolver implementations:"
find . -name "*.ts" -o -name "*.js" | xargs grep -l "AdvertisementWhereInput" | grep -v "documentNodes.ts" || echo "No other files reference this type"

Length of output: 1453


AdvertisementWhereInput Definition Verified

The schema file (./schema.graphql) properly defines the AdvertisementWhereInput type with the expected isCompleted: Boolean field. Additionally, the references in resolver implementations (notably in ./src/graphql/inputs/QueryOrganizationInput.ts and ./src/graphql/types/Organization/advertisements.ts) confirm that the input type is correctly integrated and in use.

No changes are required regarding this type.


721-764:

✅ Verification successful

Verify the integration with the frontend issue.

According to the PR description, this feature is necessary for addressing a frontend issue in the talawa-admin repository (#3557). Confirm that this implementation provides all the necessary data required by the frontend.


🌐 Web query:

What is infinite scroll pagination in GraphQL and how does it typically work with advertisements?

💡 Result:

Infinite scroll pagination in GraphQL dynamically loads content as users scroll, avoiding traditional page navigation. It combines GraphQL's pagination capabilities with frontend techniques to fetch and append data continuously. Here's how it works and interacts with advertisements:

GraphQL Pagination Mechanics

  • Offset-based pagination uses first/limit and offset arguments to fetch chunks of data (e.g., { posts(first: 10, offset: 0) { ... } })[1][3]. Apollo Client's fetchMore() method simplifies this by appending new results to existing data[7][9].
  • Cursor-based pagination relies on unique identifiers (e.g., after: "cursor") for efficient record tracking, often using Relay-compatible connections with edges and pageInfo[6][10].

Infinite Scroll Implementation

  1. Scroll detection:
    • Scroll event listeners calculate proximity to the bottom using scrollTop, clientHeight, and scrollHeight[1][7].
    • Modern approaches use IntersectionObserver to trigger loads when a sentinel element becomes visible[1][9].
  2. Data fetching:
    • Each scroll triggers a GraphQL query for the next data chunk.
    • Apollo Client caches and merges results automatically[4][7].

Advertisement Integration Challenges

  • Ad visibility:
    • Dynamically loaded ads risk low viewability as users scroll past them quickly. Unviewed ads dilute advertiser bids over time[2][8].
    • Solutions include lazy-loading ads when they approach the viewport and using debounced refresh for sticky ad units[5].
  • Performance impact:
    • Continuous ad loading can slow page speed. GPT (Google Publisher Tag) optimizations like Single Request Architecture (SRA) help[5].
    • Ad density must balance revenue goals with user experience to avoid "ad fatigue"[2][8].

Typical Workflow with Ads

// Example using IntersectionObserver for ads
const adObserver = new IntersectionObserver((entries) => {
  entries.forEach(entry => {
    if (entry.isIntersecting) {
      googletag.pubads().refresh([adSlot]);
    }
  });
});
adObserver.observe(adPlaceholderElement);

// GraphQL data fetch
const { fetchMore } = useQuery(GET_POSTS, {
  variables: { offset: 0, limit: 10 },
});

Key considerations:

  • Use rootMargin to preload ads before they enter the viewport[5][9].
  • Reset ad slots on new page segments to avoid duplicate impressions[5].
  • Monitor Content-to-Ad ratios to maintain SEO and compliance[5][10].

While infinite scroll boosts engagement[8], publishers often see declining RPMs due to ad stacking and poor visibility[2][5]. Hybrid approaches—like combining scroll with occasional "Load More" buttons—can mitigate these issues while preserving user experience[8][10].

Citations:


Action: Confirm GraphQL Query Provides Complete Infinite Scroll Data for Advertisements

The query for advertisements correctly implements cursor‑based pagination (using first, last, after, before) and returns both the edges (with all essential advertisement fields) and the associated pageInfo (including startCursor, endCursor, hasNextPage, and hasPreviousPage). These details align with typical infinite scroll pagination requirements, ensuring that the frontend in the talawa-admin repository (#3557) will receive the full set of data it needs for dynamically loading additional advertisements.

  • Confirm that the frontend integration hooks into these pagination fields correctly.
  • Verify that the filter argument (where) is handled appropriately in practice.

@palisadoes palisadoes added the ignore-sensitive-files-pr The contributor has a legitimate reason for editiing protected files label Apr 13, 2025
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: 8

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between ecca390 and 0434591.

📒 Files selected for processing (2)
  • src/graphql/types/Organization/advertisements.ts (6 hunks)
  • test/graphql/types/Organization/advertisement.test.ts (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (2)
test/graphql/types/Organization/advertisement.test.ts (3)
test/graphql/types/client.ts (1)
  • mercuriusClient (7-9)
test/server.ts (1)
  • server (12-27)
test/routes/graphql/documentNodes.ts (2)
  • Query_advertisements (721-765)
  • Mutation_createAdvertisement (767-773)
src/graphql/types/Organization/advertisements.ts (2)
src/utilities/defaultGraphQLConnection.ts (4)
  • createGraphQLConnectionWithWhereSchema (147-153)
  • transformGraphQLConnectionArgumentsWithWhere (163-184)
  • defaultGraphQLConnectionArgumentsSchema (41-62)
  • ParsedDefaultGraphQLConnectionArgumentsWithWhere (28-36)
src/graphql/inputs/QueryOrganizationInput.ts (1)
  • AdvertisementWhereInput (64-76)
🪛 GitHub Actions: Pull request workflow
test/graphql/types/Organization/advertisement.test.ts

[error] 56-56: Type '{ isCompleted: false; }' is not assignable to type 'null | undefined'.


[error] 110-110: Type '{ isCompleted: false; }' is not assignable to type 'null | undefined'.


[error] 162-162: Type '{ isCompleted: false; }' is not assignable to type 'null | undefined'.


[error] 232-232: Type '{ isCompleted: false; }' is not assignable to type 'null | undefined'.


[error] 298-298: Type '{ isCompleted: true; }' is not assignable to type 'null | undefined'.


[error] 486-486: Type '{ isCompleted: false; }' is not assignable to type 'null | undefined'.


[error] 668-668: Type '{ isCompleted: true; }' is not assignable to type 'null | undefined'.

⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Analyse Code With CodeQL (typescript)
🔇 Additional comments (5)
test/graphql/types/Organization/advertisement.test.ts (1)

181-313: Verify Test Assertions for “Active” vs. “Completed”
The tests confirm that a banner advertisement with start/end dates in the future is considered active, and one with past end dates is considered completed. The logic and assertions look correct. Good job validating edges, page info, and ensuring completeness.

🧰 Tools
🪛 GitHub Actions: Pull request workflow

[error] 232-232: Type '{ isCompleted: false; }' is not assignable to type 'null | undefined'.


[error] 298-298: Type '{ isCompleted: true; }' is not assignable to type 'null | undefined'.

src/graphql/types/Organization/advertisements.ts (4)

149-157: Well-Structured Argument Destructuring
Extracting cursor, isInversed, limit, and where from parsedArgs is clearly laid out and aids readability. Good job keeping the code maintainable.


183-197: Check Timestamps for Completed/Active Condition
You rely on lt(advertisementsTable.endAt, today) to gauge completion status. This is correct for events that ended before the current time, but confirm that the time zones are consistent and that you handle edge-cases (e.g., if endAt is exactly now).


265-281: Double Check Future Ads
For extendedArgs.isCompleted === false, you check gt(advertisementsTable.endAt, today). Confirm that an advertisement that started in the past but ends in the future is considered ongoing (thus “active”), in line with your requirements.


26-57:

❓ Verification inconclusive

Validate Cursor Schema Reference
You are merging advertisementWhereSchema into the connection arguments. Verify the cursor schema references when mixing where data with pagination. Consider adding more thorough tests to confirm that cursors behave correctly if where.isCompleted is set, while also ensuring that no query errors occur.


🏁 Script executed:

#!/bin/bash
# Scan for any references to advertisementWhereSchema usage
# to ensure all cursor transformations handle optional fields properly.
rg -A 5 'advertisementWhereSchema'

Length of output: 968


Cursor Schema and Pagination Validation
The merged usage of advertisementWhereSchema in the connection arguments appears correct, with its definition (an optional object including isCompleted) properly incorporated. However, please verify that the cursor transformation logic behaves as expected when a where clause (particularly with isCompleted set) is present. It would be beneficial to add tests that:

  • Confirm the correct parsing of a valid cursor (and proper error handling for invalid cursors).
  • Ensure that merging the where data does not interfere with pagination logic or lead to unexpected query errors.

@PalisadoesFoundation PalisadoesFoundation deleted a comment from codecov bot Apr 13, 2025
Copy link

codecov bot commented Apr 14, 2025

Codecov Report

Attention: Patch coverage is 65.44118% with 47 lines in your changes missing coverage. Please review.

Project coverage is 59.60%. Comparing base (266adb1) to head (5cb1b33).
Report is 1 commits behind head on develop-postgres.

Files with missing lines Patch % Lines
src/graphql/types/Organization/advertisements.ts 62.09% 47 Missing ⚠️
Additional details and impacted files
@@                 Coverage Diff                  @@
##           develop-postgres    #3444      +/-   ##
====================================================
+ Coverage             59.07%   59.60%   +0.52%     
====================================================
  Files                   523      523              
  Lines                 40674    40782     +108     
  Branches               1735     1786      +51     
====================================================
+ Hits                  24030    24307     +277     
+ Misses                16635    16464     -171     
- Partials                  9       11       +2     

☔ 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 (6)
test/routes/graphql/documentNodes.ts (1)

767-773: 🧹 Nitpick (assertive)

Fix inconsistency in mutation operation name.

There is a naming inconsistency in the GraphQL operation. The export constant is named Mutation_createAdvertisement, but the operation inside the GraphQL string is named Mutation_createAd. For consistency and clarity, these names should match.

-  mutation Mutation_createAd($input: MutationCreateAdvertisementInput!) {
+  mutation Mutation_createAdvertisement($input: MutationCreateAdvertisementInput!) {
test/graphql/types/Organization/advertisement.test.ts (4)

74-187: Consolidate “empty active ads” & “empty complete ads” tests.
These two tests are nearly identical except for the isCompleted flag. Consider merging them into a single parameterized test for clarity, in line with previous review suggestions.


189-329: DRY up repeated organization creation.
The code for creating a new organization is duplicated in multiple test blocks. Extract this into a helper function to comply with DRY (Don’t Repeat Yourself), as previously suggested.


331-704: Consider a parameterized test for pagination checks.
You repeat advertisement creation and pagination checks for completed and non-completed ads. Consolidate these into a parameterized test to reduce duplication, as noted in previous feedback.


25-72: 🧹 Nitpick (assertive)

Test suite naming mismatch.
This suite is named "Organization.blockedUsers Field" but is testing advertisement queries. Consider renaming the suite to match the relevant advertisement functionality.

- suite("Organization.blockedUsers Field", () => {
+ suite("Organization.advertisements Field", () => {
src/graphql/types/Organization/advertisements.ts (1)

185-198: Factor out repeated completion checks.
The branching logic for extendedArgs.isCompleted is duplicated in both the isInversed and non-inversed branches. A small utility function for building where conditions could minimize repetition.

Also applies to: 207-223, 227-260, 261-283

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 0434591 and 32b035c.

📒 Files selected for processing (5)
  • schema.graphql (2 hunks)
  • src/graphql/types/Organization/advertisements.ts (6 hunks)
  • test/graphql/types/Organization/advertisement.test.ts (1 hunks)
  • test/graphql/types/gql.tada.d.ts (2 hunks)
  • test/routes/graphql/documentNodes.ts (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (2)
test/graphql/types/Organization/advertisement.test.ts (3)
test/graphql/types/client.ts (1)
  • mercuriusClient (7-9)
test/routes/graphql/documentNodes.ts (4)
  • Query_signIn (191-218)
  • Mutation_createOrganization (370-377)
  • Query_advertisements (721-765)
  • Mutation_createAdvertisement (767-773)
test/server.ts (1)
  • server (12-27)
src/graphql/types/Organization/advertisements.ts (3)
src/utilities/defaultGraphQLConnection.ts (4)
  • createGraphQLConnectionWithWhereSchema (147-153)
  • transformGraphQLConnectionArgumentsWithWhere (163-184)
  • defaultGraphQLConnectionArgumentsSchema (41-62)
  • ParsedDefaultGraphQLConnectionArgumentsWithWhere (28-36)
src/graphql/inputs/QueryOrganizationInput.ts (1)
  • AdvertisementWhereInput (64-76)
src/drizzle/tables/advertisements.ts (1)
  • advertisementsTable (20-109)
⏰ 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 (10)
schema.graphql (2)

143-147: Well-structured input type with good documentation.

The AdvertisementWhereInput input type is properly defined with clear documentation and a well-named isCompleted field to support filtering advertisements by completion status. The documentation is clear and descriptive.


2896-2904: Good implementation of the where parameter in advertisements field.

The advertisements field in the Organization type has been correctly updated to include the new where parameter of type AdvertisementWhereInput. The changes follow the established pattern of other connection fields and the documentation clearly explains the purpose of the parameter.

test/routes/graphql/documentNodes.ts (1)

721-765: Well-structured query for organization advertisements.

The Query_advertisements is properly structured to fetch advertisements with all necessary fields and includes support for the new where parameter for filtering by completion status. The pagination parameters are also correctly implemented.

test/graphql/types/gql.tada.d.ts (2)

11-11: Confirm optional status of isCompleted.
The newly added AdvertisementWhereInput type correctly marks isCompleted as an optional boolean. This aligns well with the tests passing objects like { isCompleted: false }.


61-61: Updated HasUserVoted schema looks good.
The revised structure with separate hasVoted and voteType fields is clearer and aligns with best practices for boolean flags.

test/graphql/types/Organization/advertisement.test.ts (1)

13-23: Positive sign-in setup.
The shared sign-in approach is succinct and easily reused, setting a good foundation for authenticated tests.

src/graphql/types/Organization/advertisements.ts (4)

20-24: Schema definition aligns with usage.
Defining advertisementWhereSchema as an optional object with an optional isCompleted boolean matches the AdvertisementWhereInput and test usage, eliminating past pipeline errors.


26-57: Robust argument transformation.
Using createGraphQLConnectionWithWhereSchema with a custom transform helps keep code organized. Ensure any future fields in AdvertisementWhereInput are handled similarly.


75-81: Inline “where” argument on field definition is coherent.
Defining where: t.arg({ ... }) here keeps the schema consistent with the Zod transformation. Good job aligning front-end queries with back-end logic.


150-158: Improved type inference.
Casting parsed arguments to ParsedDefaultGraphQLConnectionArgumentsWithWhere clarifies the shape of extendedArgs, avoiding confusion around the where property.

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 (4)
test/graphql/types/Organization/advertisement.test.ts (4)

251-251: Remove debug console.log statement

The console.log statement should be removed as it will clutter test output.

- console.log("Active advertisements are: ", activeAdvertisements);

76-95: 🛠️ Refactor suggestion

Extract common organization creation logic

The organization creation code is duplicated across multiple test blocks. Consider extracting this into a helper function to improve maintainability and follow the DRY principle.

// Helper function to create a test organization
async function createTestOrganization() {
  const createOrgResult = await mercuriusClient.mutate(
    Mutation_createOrganization,
    {
      headers: { authorization: `bearer ${authToken}` },
      variables: {
        input: {
          name: `Advertisements Test Org ${faker.string.uuid()}`,
          description: "Org to test advertisements",
          countryCode: "us",
          state: "CA",
          city: "San Francisco",
          postalCode: "94101",
          addressLine1: "100 Test St",
          addressLine2: "Suite 1",
        },
      },
    },
  );
  const orgId = createOrgResult.data?.createOrganization?.id;
  assertToBeNonNullish(orgId);
  return orgId;
}

Also applies to: 132-151, 191-210, 333-352, 519-538


359-477: 🛠️ Refactor suggestion

Create helper for multiple advertisement creation

The pagination tests create multiple advertisements with almost identical code. Consider creating a helper function to reduce duplication and improve maintainability.

// Helper function to create multiple advertisements
async function createMultipleAdvertisements(
  orgId: string, 
  count: number, 
  isActive: boolean = true
) {
  const endDate = isActive ? "2030-02-02" : "2025-02-02";
  
  for (let i = 1; i <= count; i++) {
    await mercuriusClient.mutate(Mutation_createAdvertisement, {
      headers: { authorization: `bearer ${authToken}` },
      variables: {
        input: {
          organizationId: orgId,
          name: `Linux session ${i}`,
          type: "banner",
          startAt: new Date("2025-01-01").toISOString(),
          endAt: new Date(endDate).toISOString(),
          description: "learn about basics",
          attachments: undefined,
        },
      },
    });
  }
}

Also applies to: 545-663


74-187: 🧹 Nitpick (assertive)

Consider merging "empty active ads" and "empty completed ads" tests

These two tests differ only in the isCompleted flag value. Consider parameterizing the test to reduce duplication.

[true, false].forEach(isCompleted => {
  test(`should return an empty ${isCompleted ? 'completed' : 'active'} ads connection`, async () => {
    // Test implementation with isCompleted as parameter
  });
});
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 32b035c and 213d01d.

📒 Files selected for processing (1)
  • test/graphql/types/Organization/advertisement.test.ts (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
test/graphql/types/Organization/advertisement.test.ts (3)
test/graphql/types/client.ts (1)
  • mercuriusClient (7-9)
test/routes/graphql/documentNodes.ts (4)
  • Query_signIn (191-218)
  • Mutation_createOrganization (370-377)
  • Query_advertisements (721-765)
  • Mutation_createAdvertisement (767-773)
test/server.ts (1)
  • server (12-27)
⏰ 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 (5)
test/graphql/types/Organization/advertisement.test.ts (5)

25-25: Test suite name is accurate and clear

The test suite name "Organization.advertisement Field" correctly describes the functionality being tested.


56-58: Good implementation of the AdvertisementWhereInput filter

The where parameter with isCompleted: false correctly uses the new filter capability that this PR introduces.


112-114: Filter for active advertisements implemented correctly

Using isCompleted: false properly filters for active advertisements.


312-314: Correctly filtering for completed advertisements

The filter parameter isCompleted: true is properly used to get completed advertisements.


504-506: The implementation correctly uses the new filter parameter

The isCompleted filter parameter is properly used in pagination tests for both active and completed advertisements.

Also applies to: 690-692

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

♻️ Duplicate comments (1)
test/graphql/types/Organization/advertisement.test.ts (1)

117-154: ⚠️ Potential issue

Fix test name and filter mismatch.

In this test named "should return an empty complete ads connection", you're using isCompleted: false which would filter for active advertisements rather than completed ones.

Change the filter to match the test name:

-                        where: {
-                            isCompleted: false,
-                        },
+                        where: {
+                            isCompleted: true,
+                        },
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 213d01d and e9342f5.

📒 Files selected for processing (1)
  • test/graphql/types/Organization/advertisement.test.ts (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
test/graphql/types/Organization/advertisement.test.ts (3)
test/graphql/types/client.ts (1)
  • mercuriusClient (7-9)
test/routes/graphql/documentNodes.ts (4)
  • Mutation_createOrganization (370-377)
  • Query_signIn (191-218)
  • Query_advertisements (721-765)
  • Mutation_createAdvertisement (767-773)
test/server.ts (1)
  • server (12-27)
🪛 Biome (1.9.4)
test/graphql/types/Organization/advertisement.test.ts

[error] 488-488: Forbidden non-null assertion.

Unsafe fix: Replace with optional chain operator ?. This operator includes runtime checks, so it is safer than the compile-only non-null assertion operator

(lint/style/noNonNullAssertion)

🪛 GitHub Actions: Pull request workflow
test/graphql/types/Organization/advertisement.test.ts

[error] 488-488: lint/style/noNonNullAssertion: Forbidden non-null assertion. Replace with optional chain operator ?.


[error] 1-1: Some errors were emitted while running checks.

⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Analyse Code With CodeQL (typescript)
🔇 Additional comments (2)
test/graphql/types/Organization/advertisement.test.ts (2)

260-312: Great test for unspecified completion status filter.

This test correctly verifies that when isCompleted is not specified, both active and completed advertisements are returned, which is crucial functionality for the PR.


607-659: Comprehensive field validation test.

The test effectively validates all the essential advertisement fields when fetched, ensuring the GraphQL query returns the expected data structure.

@bandhan-majumder
Copy link
Author

@palisadoes @disha1202 PTAL

@palisadoes palisadoes merged commit 0fac5c2 into PalisadoesFoundation:develop-postgres Apr 14, 2025
19 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
ignore-sensitive-files-pr The contributor has a legitimate reason for editiing protected files
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants