Skip to content

Fix getting the collections and projects count from TinyBird#108

Merged
borfast merged 1 commit intomainfrom
bugfix/ins-225-collections-total-number-returned-in-the-api-is-not-correct
Mar 17, 2025
Merged

Fix getting the collections and projects count from TinyBird#108
borfast merged 1 commit intomainfrom
bugfix/ins-225-collections-total-number-returned-in-the-api-is-not-correct

Conversation

@borfast
Copy link
Copy Markdown
Contributor

@borfast borfast commented Mar 17, 2025

The TinyBird endpoint for the collections and projects list require a separate query to get the total count but our backend API is only making one request for the data, so the total it returns to the frontend is the total number of values in the query result, not the total available in TinyBird.

The ticket in Linear is here.

Summary by CodeRabbit

  • New Features
    • Total collections are now calculated more accurately by retrieving count data directly from an external data source.
    • Total projects are now calculated more accurately by fetching project count data from an external source.
  • Bug Fixes
    • Improved error logging messages for clarity when fetching collection and project lists from TinyBird.

@borfast borfast self-assigned this Mar 17, 2025
@borfast borfast added the bug Something isn't working label Mar 17, 2025
@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Mar 17, 2025

Walkthrough

The pull request introduces new type definitions, CollectionCount and ProjectCount, and modifies the logic for calculating the total number of collections and projects. The implementation now retrieves both counts from Tinybird via separate API calls, updating the respective total properties in the returned data. Additionally, the error logging messages are refined to specify issues related to fetching the collection and project lists from Tinybird.

Changes

File Change Summary
frontend/.../collection/index.ts Added a new type CollectionCount with a count(id): number field; updated the logic to retrieve the collection count from Tinybird via a new API call; refined error logging.
frontend/.../project/index.ts Added a new type ProjectCount with a count(id): number field; updated the logic to retrieve the project count from Tinybird via a new API call; refined error logging.

Suggested reviewers

  • gaspergrom
  • emlimlf

Possibly related PRs

  • Collections adjustments #61: The changes in the main PR, which involve the introduction of a new type definition and modifications to the collection count logic, are related to the changes in the retrieved PR that also involve modifications to the collection structure, specifically the removal of properties from collection objects in the same file.

Tip

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

📜 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 ec3d0faaa407a61a748e55d973db5d90c209df22 and d5ae688.

📒 Files selected for processing (2)
  • frontend/server/api/collection/index.ts (1 hunks)
  • frontend/server/api/project/index.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • frontend/server/api/collection/index.ts
  • frontend/server/api/project/index.ts

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Copy Markdown

@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)
frontend/server/api/collection/index.ts (4)

44-48: Good addition of the separate count query.

The implementation correctly adds a separate query to get the total count of collections from TinyBird, which aligns with the PR objective to fix the collection count issue.

However, consider making this second API call conditional on the count parameter to avoid unnecessary requests when the total count isn't needed.

        type CollectionCount = {'count(id)': number};
-       const collectionCountResult = await fetchFromTinybird<CollectionCount[]>('/v0/pipes/collections_list.json', {
-           count: true,
-       });
+       let collectionCount = 0;
+       if (count) {
+           const collectionCountResult = await fetchFromTinybird<CollectionCount[]>('/v0/pipes/collections_list.json', {
+               count: true,
+           });
+           collectionCount = collectionCountResult.data[0]?.['count(id)'] || 0;
+       }

52-52: Update the total property to use the conditional count.

If you implement the conditional fetching suggested above, update this line accordingly.

-           total: collectionCountResult.data[0]?.['count(id)'] || 0,
+           total: count ? collectionCount : 0,

58-58: Consider enhancing error handling for multiple API calls.

The error message has been improved to be more specific, but it doesn't differentiate between errors from the two API calls. Consider capturing and logging both types of errors distinctly.

-       console.error('Error fetching collection list from TinyBird:', error);
+       console.error('Error in collection API:', error instanceof Error ? error.message : String(error));
+       console.error('Error details:', error);

44-52: Consider a more performant approach in the future.

While the current implementation correctly addresses the immediate issue, making two separate API calls to the same endpoint may impact performance. In the future, consider working with the TinyBird team to modify the endpoint to return both paginated data and total count in a single response.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 98c9440 and 60a1aadcef50dc0e5f4c10d3488eff4d6d2f60de.

📒 Files selected for processing (1)
  • frontend/server/api/collection/index.ts (1 hunks)

@borfast borfast force-pushed the bugfix/ins-225-collections-total-number-returned-in-the-api-is-not-correct branch from 60a1aad to d2400d6 Compare March 17, 2025 15:20
@borfast borfast changed the title Fix getting the collections count from TinyBird Fix getting the collections and projects count from TinyBird Mar 17, 2025
@borfast borfast requested a review from gaspergrom March 17, 2025 15:21
Copy link
Copy Markdown

@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)
frontend/server/api/collection/index.ts (1)

44-48: Use a more descriptive alias for 'count(id)'.

If allowed by the Tinybird pipeline, consider aliasing 'count(id)' to a clearer property name, such as total_count, to improve readability in this code.

frontend/server/api/project/index.ts (1)

59-63: Use a more descriptive alias for 'count(id)'.

Similarly, consider aliasing 'count(id)' to something like total_count in the Tinybird query for better clarity.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 60a1aadcef50dc0e5f4c10d3488eff4d6d2f60de and d2400d6562c63448b70e108337ccfa83641ef65d.

📒 Files selected for processing (2)
  • frontend/server/api/collection/index.ts (2 hunks)
  • frontend/server/api/project/index.ts (1 hunks)
🔇 Additional comments (4)
frontend/server/api/collection/index.ts (2)

52-52: Good use of a fallback for empty data.

Providing a default value of 0 ensures the endpoint avoids crashes when collectionCountResult.data is empty or malformed.


58-58: More descriptive error message.

Logging the specific source (TinyBird) makes troubleshooting easier.

frontend/server/api/project/index.ts (2)

67-67: Nice fallback for missing data.

Defaulting total to 0 prevents runtime errors in case of an empty result set.


73-73: Clearer error message aids debugging.

Specifying that the error occurred while fetching from Tinybird is helpful for pinpointing issues quickly.

@borfast borfast force-pushed the bugfix/ins-225-collections-total-number-returned-in-the-api-is-not-correct branch from d2400d6 to ec3d0fa Compare March 17, 2025 15:31
Copy link
Copy Markdown

@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)
frontend/server/api/project/index.ts (2)

59-67: Consider potential performance impact of multiple API calls.

While the implementation correctly solves the issue of getting accurate counts, be aware that it introduces an additional API call. For high-traffic scenarios, you might want to consider:

  1. Implementing caching for the count results
  2. Only making the count request when the count parameter is true
  3. Exploring if TinyBird can return both the paginated results and total count in a single request

59-63: Consider extracting common patterns if similar code exists elsewhere.

According to the AI summary, similar changes were made in the collection API. If these patterns are repeated across multiple files, consider extracting this functionality into a reusable utility function to promote DRY principles.

// Example utility function
async function fetchWithTotalCount<T, CountT extends {'count(id)': number}>(
  endpoint: string, 
  params: Record<string, any>
): Promise<{items: T[], totalCount: number}> {
  const itemsResult = await fetchFromTinybird<T[]>(endpoint, params);
  const countResult = await fetchFromTinybird<CountT[]>(endpoint, { count: true });
  
  return {
    items: itemsResult.data,
    totalCount: countResult.data[0]?.['count(id)'] || 0
  };
}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between d2400d6562c63448b70e108337ccfa83641ef65d and ec3d0faaa407a61a748e55d973db5d90c209df22.

📒 Files selected for processing (2)
  • frontend/server/api/collection/index.ts (1 hunks)
  • frontend/server/api/project/index.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • frontend/server/api/collection/index.ts
🔇 Additional comments (3)
frontend/server/api/project/index.ts (3)

59-63: Good implementation of a separate count query.

The introduction of a specific type for the count result and making a separate API call to get the total project count addresses the issue mentioned in the PR objectives. This ensures the frontend receives the accurate total count regardless of pagination parameters.


67-67: LGTM! Robust handling of the count result.

The implementation properly handles potential edge cases by using the optional chaining operator (?.) and providing a fallback value of 0. This ensures the application doesn't break if the count result is unexpected.


73-73: Improved error logging.

The updated error message now clearly indicates that the error occurred while fetching the project list from TinyBird, making debugging easier.

Signed-off-by: Raúl Santos <4837+borfast@users.noreply.github.com>
@borfast borfast force-pushed the bugfix/ins-225-collections-total-number-returned-in-the-api-is-not-correct branch from ec3d0fa to d5ae688 Compare March 17, 2025 15:58
@borfast borfast merged commit 12650a6 into main Mar 17, 2025
3 checks passed
@borfast borfast deleted the bugfix/ins-225-collections-total-number-returned-in-the-api-is-not-correct branch March 17, 2025 16:31
@borfast borfast assigned borfast and unassigned borfast May 2, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants