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

Feat: Cursor based Pagination #479

Merged
merged 6 commits into from
Jun 11, 2024
Merged

Conversation

mit-27
Copy link
Contributor

@mit-27 mit-27 commented Jun 4, 2024

/claim #479

Hello @naelob and @rflihxyz , currently I have added cursor pagination for GET: crm/contacts Unified API to validate the format of the response. Let me know if there are any changes required. then Upon your approval, I will implement cursor pagination for all unified APIs. Thanks.

API response Format

{
  data: [...],
  prev_cursor: value,
  next_cursor: value
}

Summary by CodeRabbit

  • New Features

    • Introduced pagination support in the contact list with pageSize and cursor parameters.
  • Improvements

    • Enhanced contact retrieval with more efficient pagination logic.
  • Testing Enhancements

    • Adjusted contact sync schedule to every 2 minutes for testing purposes.

Copy link

vercel bot commented Jun 4, 2024

@mit-27 is attempting to deploy a commit to the Panora Team on Vercel.

A member of the Team first needs to authorize it.

Copy link

changeset-bot bot commented Jun 4, 2024

⚠️ No Changeset found

Latest commit: a53062a

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

Copy link
Contributor

coderabbitai bot commented Jun 4, 2024

Important

Review skipped

Auto reviews are disabled on this repository.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

The changes introduce cursor-based pagination to the CRM API's contact management. This includes modifications to the contact.controller.ts and contact.service.ts to handle pagination parameters, and the creation of a GetContactsQueryDto for structured query handling. Additionally, the contact sync schedule has been updated to run every 2 minutes for testing purposes.

Changes

Files Change Summary
packages/api/src/crm/contact/contact.controller.ts Added UsePipes, ValidationPipe, and GetContactsQueryDto imports; updated getContacts method.
packages/api/src/crm/contact/services/contact.service.ts Added pagination logic and modified getUnifiedContacts method to handle pageSize and cursor.
packages/api/src/crm/contact/sync/sync.service.ts Changed cron schedule for syncing contacts from every 8 hours to every 2 minutes for testing.
packages/api/src/crm/contact/types/dto/get-contacts-query.dto.ts Created GetContactsQueryDto for handling pagination query parameters.

Sequence Diagram(s) (Beta)

sequenceDiagram
    participant User
    participant Controller
    participant Service
    participant Database
    
    User->>+Controller: GetContacts(pageSize, cursor)
    Controller->>+Service: getUnifiedContacts(pageSize, cursor)
    Service->>+Database: Fetch contacts with cursor
    Database-->>-Service: Return contacts, prev_cursor, next_cursor
    Service-->>-Controller: Return contacts, prev_cursor, next_cursor
    Controller-->>-User: Return paginated contacts
Loading

Assessment against linked issues

Objective (Issue #) Addressed Explanation
Implement cursor-based pagination (#430)
Ensure pagination parameters are handled in controller (#430)
Update cron schedule for contact syncing (#430)

Poem

In fields of code, where data flows,
A rabbit hops, where logic grows.
With cursors set and pages turned,
Contact lists are now well-learned.
Syncs that tick like clockwork fine,
Every two minutes, right on time.
Hopping through the data stream,
CodeRabbit makes the system gleam. 🐇✨


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>.
    • 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 generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @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 as 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 resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configration 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

@greptile-apps greptile-apps bot left a comment

Choose a reason for hiding this comment

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

PR Summary

  • Added cursor-based pagination to GET: crm/contacts endpoint
  • Introduced unique constraint and default value for created_at in crm_contacts model and table
  • Modified CRON schedule in sync.service.ts for testing
  • Added GetContactsQueryDto class for pagination support
  • Updated Swagger spec to include pagination parameters

Comment on lines 118 to 119
: 'contact_id' in source_contact
? String(source_contact.contact_id)
: undefined;
? String(source_contact.contact_id)
Copy link

Choose a reason for hiding this comment

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

Corrected indentation for better readability.

Comment on lines 503 to 507
const defaultPageSize = 10;

if (cursor) {
const isCursorPresent = await this.prisma.crm_contacts.findFirst({
where: {
Copy link

Choose a reason for hiding this comment

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

Check if the provided cursor exists and throw NotFoundError if it does not.


@IsOptional()
@IsDefined()
@Transform(({ value }) => value === 'true' ? true : value === 'false' ? false : value)
Copy link

Choose a reason for hiding this comment

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

@IsDefined() is redundant when used with @IsOptional(). Remove @IsDefined().

@Transform(p => Buffer.from(p.value, 'base64').toString())
@IsUUID()
cursor: string;

Copy link

Choose a reason for hiding this comment

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

Use @IsBase64() to validate the cursor before transforming it.

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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 7b21d0b and 57b6824.

Files selected for processing (7)
  • packages/api/prisma/schema.prisma (1 hunks)
  • packages/api/scripts/init.sql (1 hunks)
  • packages/api/src/crm/contact/contact.controller.ts (3 hunks)
  • packages/api/src/crm/contact/services/contact.service.ts (5 hunks)
  • packages/api/src/crm/contact/sync/sync.service.ts (1 hunks)
  • packages/api/src/crm/contact/types/dto/get-contacts-query.dto.ts (1 hunks)
  • packages/api/swagger/swagger-spec.json (1 hunks)
Files skipped from review due to trivial changes (1)
  • packages/api/src/crm/contact/sync/sync.service.ts
Additional comments not posted (10)
packages/api/src/crm/contact/types/dto/get-contacts-query.dto.ts (3)

7-11: The implementation of the remote_data field with a custom transformer to handle boolean values as strings is appropriate and follows best practices for handling boolean query parameters.


13-16: The use of the @Transform decorator to convert pageSize to a number ensures type safety and is a good practice for pagination parameters.


18-21: Transforming the cursor from a base64 string to a UUID string enhances security by obscuring direct database identifiers, which is a recommended practice.

packages/api/src/crm/contact/contact.controller.ts (3)

11-12: The addition of UsePipes and ValidationPipe along with the import of GetContactsQueryDto are appropriate for enabling validation and handling pagination in the getContacts method.

Also applies to: 31-31


61-72: The addition of pageSize and cursor query parameters, along with their documentation in the Swagger API, enhances the API's functionality and discoverability.


76-92: The modifications in the getContacts method to use GetContactsQueryDto for handling pagination are correctly implemented. The method correctly handles the pageSize and cursor parameters for pagination.

packages/api/src/crm/contact/services/contact.service.ts (2)

14-14: The addition of imports related to error handling and additional services is appropriate and supports the expanded functionality of the service.


Line range hint 496-631: The implementation of pagination logic in the getContacts method, including handling of pageSize and cursor parameters, is correctly done. The method appropriately checks for the presence of a cursor and handles pagination boundaries.

packages/api/scripts/init.sql (1)

468-475: The addition of a default value for created_at and a unique constraint in the crm_contacts table enhances data integrity and prevents duplicate entries, aligning with the objectives of the PR.

packages/api/swagger/swagger-spec.json (1)

1554-1569: Addition of pagination parameters for /crm/contacts endpoint.

The addition of pageSize and cursor parameters aligns with the PR objectives to implement cursor-based pagination. This change is crucial for handling large datasets efficiently and avoiding issues like double entries mentioned in the linked issue. Good job on updating the Swagger documentation to reflect these new query parameters.

@@ -164,7 +164,7 @@ model crm_contacts {
id_crm_contact String @id(map: "pk_crm_contacts") @db.Uuid
first_name String
last_name String
created_at DateTime @db.Timestamp(6)
created_at DateTime @unique(map: "force_createdat_unique") @default(now()) @db.Timestamp(6)
Copy link
Contributor

Choose a reason for hiding this comment

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

Potential issue with unique constraint on created_at.

The addition of a unique constraint on the created_at field might lead to issues in environments with high write volumes, as multiple contacts could potentially be created at the same exact timestamp. Consider if this constraint is necessary or if it could be replaced with another unique identifier.

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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 57b6824 and 1cb54a4.

Files selected for processing (3)
  • packages/api/src/crm/contact/contact.controller.ts (3 hunks)
  • packages/api/src/crm/contact/sync/sync.service.ts (2 hunks)
  • packages/api/src/crm/contact/types/dto/get-contacts-query.dto.ts (1 hunks)
Files skipped from review as they are similar to previous changes (1)
  • packages/api/src/crm/contact/types/dto/get-contacts-query.dto.ts
Additional context used
Biome
packages/api/src/crm/contact/contact.controller.ts

[error] 78-78: Decorators are not valid here. (parse)

Decorators are only valid on class declarations, class expressions, and class methods.
You can enable parameter decorators by setting the unsafeParameterDecoratorsEnabled option to true in your configuration file.


[error] 79-79: Decorators are not valid here. (parse)

Decorators are only valid on class declarations, class expressions, and class methods.
You can enable parameter decorators by setting the unsafeParameterDecoratorsEnabled option to true in your configuration file.


[error] 120-120: Decorators are not valid here. (parse)

Decorators are only valid on class declarations, class expressions, and class methods.
You can enable parameter decorators by setting the unsafeParameterDecoratorsEnabled option to true in your configuration file.


[error] 121-121: Decorators are not valid here. (parse)

Decorators are only valid on class declarations, class expressions, and class methods.
You can enable parameter decorators by setting the unsafeParameterDecoratorsEnabled option to true in your configuration file.


[error] 148-148: Decorators are not valid here. (parse)

Decorators are only valid on class declarations, class expressions, and class methods.
You can enable parameter decorators by setting the unsafeParameterDecoratorsEnabled option to true in your configuration file.


[error] 149-149: Decorators are not valid here. (parse)

Decorators are only valid on class declarations, class expressions, and class methods.
You can enable parameter decorators by setting the unsafeParameterDecoratorsEnabled option to true in your configuration file.


[error] 150-150: Decorators are not valid here. (parse)

Decorators are only valid on class declarations, class expressions, and class methods.
You can enable parameter decorators by setting the unsafeParameterDecoratorsEnabled option to true in your configuration file.


[error] 190-190: Decorators are not valid here. (parse)

Decorators are only valid on class declarations, class expressions, and class methods.
You can enable parameter decorators by setting the unsafeParameterDecoratorsEnabled option to true in your configuration file.


[error] 191-191: Decorators are not valid here. (parse)

Decorators are only valid on class declarations, class expressions, and class methods.
You can enable parameter decorators by setting the unsafeParameterDecoratorsEnabled option to true in your configuration file.


[error] 192-192: Decorators are not valid here. (parse)

Decorators are only valid on class declarations, class expressions, and class methods.
You can enable parameter decorators by setting the unsafeParameterDecoratorsEnabled option to true in your configuration file.


[error] 217-217: Decorators are not valid here. (parse)

Decorators are only valid on class declarations, class expressions, and class methods.
You can enable parameter decorators by setting the unsafeParameterDecoratorsEnabled option to true in your configuration file.


[error] 218-218: Decorators are not valid here. (parse)

Decorators are only valid on class declarations, class expressions, and class methods.
You can enable parameter decorators by setting the unsafeParameterDecoratorsEnabled option to true in your configuration file.

packages/api/src/crm/contact/sync/sync.service.ts

[error] 32-32: Decorators are not valid here. (parse)

Decorators are only valid on class declarations, class expressions, and class methods.
You can enable parameter decorators by setting the unsafeParameterDecoratorsEnabled option to true in your configuration file.


[error] 223-223: Unexpected any. Specify a different type. (lint/suspicious/noExplicitAny)

any disables many type checking rules. Its use should be avoided.


[error] 231-231: Use === instead of ==.
== is only allowed when comparing against null (lint/suspicious/noDoubleEquals)

== is only allowed when comparing against null

Using == may be unsafe if you are relying on type coercion
Unsafe fix: Use ===


[error] 262-262: Unexpected any. Specify a different type. (lint/suspicious/noExplicitAny)

any disables many type checking rules. Its use should be avoided.


[error] 292-293: Change to an optional chain. (lint/complexity/useOptionalChain)

Unsafe fix: Change to an optional chain.


[error] 317-318: Change to an optional chain. (lint/complexity/useOptionalChain)

Unsafe fix: Change to an optional chain.


[error] 342-342: Change to an optional chain. (lint/complexity/useOptionalChain)

Unsafe fix: Change to an optional chain.


[error] 368-368: Unexpected any. Specify a different type. (lint/suspicious/noExplicitAny)

any disables many type checking rules. Its use should be avoided.

Additional comments not posted (6)
packages/api/src/crm/contact/contact.controller.ts (4)

31-31: Import statement for GetContactsQueryDto is correctly added.


61-72: Added pagination query parameters correctly.


11-12: Ensure proper configuration for ValidationPipe.


79-79: Ensure GetContactsQueryDto is correctly utilized in the method signature.

Verification successful

The GetContactsQueryDto class is correctly defined and utilized in the method signature.

  • GetContactsQueryDto is imported and used in contact.controller.ts.
  • The class is defined with appropriate decorators and transformations in get-contacts-query.dto.ts.
Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify the usage of `GetContactsQueryDto` in the project.

# Test: Search for `GetContactsQueryDto` usage in the project. Expect: Correct usage in method signatures.
rg --type typescript $'GetContactsQueryDto'

Length of output: 77



Script:

#!/bin/bash
# Description: Verify the usage of `GetContactsQueryDto` in the project.

# Test: Search for `GetContactsQueryDto` usage in the project. Expect: Correct usage in method signatures.
rg --type ts 'GetContactsQueryDto'

Length of output: 350



Script:

#!/bin/bash
# Description: Display the contents of `get-contacts-query.dto.ts` to verify the definition of `GetContactsQueryDto`.

# Test: Display the contents of the file to ensure `GetContactsQueryDto` is correctly defined.
cat packages/api/src/crm/contact/types/dto/get-contacts-query.dto.ts

Length of output: 598

Tools
Biome

[error] 79-79: Decorators are not valid here. (parse)

Decorators are only valid on class declarations, class expressions, and class methods.
You can enable parameter decorators by setting the unsafeParameterDecoratorsEnabled option to true in your configuration file.

packages/api/src/crm/contact/sync/sync.service.ts (2)

88-93: Correctly fetches user details based on the provided user ID.


372-372: Ensure proper handling of date fields in the database operations.

@ApiCustomResponse(UnifiedContactOutput)
@UseGuards(ApiKeyAuthGuard)
@Get()
@UsePipes(new ValidationPipe({ transform: true, disableErrorMessages: true }))
Copy link
Contributor

Choose a reason for hiding this comment

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

Decorator usage error: @UsePipes should not be used here.

- @UsePipes(new ValidationPipe({ transform: true, disableErrorMessages: true }))
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
@UsePipes(new ValidationPipe({ transform: true, disableErrorMessages: true }))

@naelob
Copy link
Contributor

naelob commented Jun 4, 2024

Hello @naelob and @rflihxyz , currently I have added cursor pagination for GET: crm/contacts Unified API to validate the format of the response. Let me know if there are any changes required. then Upon your approval, I will implement cursor pagination for all unified APIs. Thanks.

API response Format

{
  data: [...],
  prev_cursor: value,
  next_cursor: value
}

Summary by CodeRabbit

  • New Features

    • Introduced pagination support in the contact list with pageSize and cursor parameters.
  • Improvements

    • Enhanced contact retrieval with more efficient pagination logic.
  • Testing Enhancements

    • Adjusted contact sync schedule to every 2 minutes for testing purposes.

It sounds good for me.

Copy link

@greptile-apps greptile-apps bot left a comment

Choose a reason for hiding this comment

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

PR Summary

(updates since last review)

  • Introduced cursor-based pagination for GET: crm/contacts Unified API
  • Updated Dockerfiles to use turbo version 1.13.4
  • Removed FieldMappingModal.tsx component
  • Added id_linked_user field to EventsTable and schema
  • Enhanced error handling in CRM utilities

@@ -26,6 +28,7 @@ import {
import { ApiKeyAuthGuard } from '@@core/auth/guards/api-key.guard';
Copy link

Choose a reason for hiding this comment

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

Consider adding a brief comment explaining the purpose of the GetContactsQueryDto import for clarity.

@naelob
Copy link
Contributor

naelob commented Jun 11, 2024

/bounty 200

Copy link

algora-pbc bot commented Jun 11, 2024

💎 $200 bounty • Panora (YC S24)

Steps to solve:

  1. Start working: Comment /attempt #479 with your implementation plan
  2. Submit work: Create a pull request including /claim #479 in the PR body to claim the bounty
  3. Receive payment: 100% of the bounty is received 2-5 days post-reward. Make sure you are eligible for payouts

Additional opportunities:

  • 🔴 Livestream on Algora TV while solving this bounty & earn $200 upon merge! Make sure to have your camera and microphone on. Comment /livestream once live

Thank you for contributing to panoratech/Panora!

Add a bountyShare on socials

Attempt Started (GMT+0) Review
🟢 @mit-27 Jun 11, 2024, 1:02:13 PM #479

@mit-27
Copy link
Contributor Author

mit-27 commented Jun 11, 2024

/attempt #479

/claim #479

Algora profile Completed bounties Tech Active attempts Options
@mit-27 1 panoratech bounty
TypeScript, Python,
Jupyter Notebook & more
Cancel attempt

Copy link

algora-pbc bot commented Jun 11, 2024

💡 @mit-27 submitted a pull request that claims the bounty. You can visit your bounty board to reward.

Copy link

algora-pbc bot commented Jun 11, 2024

🎉🎈 @mit-27 has been awarded $200! 🎈🎊

@naelob naelob merged commit e9d6ea2 into panoratech:main Jun 11, 2024
9 of 12 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

feat: Cursor Based Pagination
2 participants