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: persons endpoint #18

Merged
merged 14 commits into from
Jul 26, 2024
Merged

feat: persons endpoint #18

merged 14 commits into from
Jul 26, 2024

Conversation

joscha
Copy link
Member

@joscha joscha commented Jul 23, 2024

Summary by CodeRabbit

  • New Features

    • Introduced automatic reviews for draft submissions via the .coderabbit.yaml configuration.
    • Added eof_newline option for YAML formatting to control end-of-file newlines.
    • Enhanced person API with new request and response types, improving data handling.
    • Implemented a new structure for paginated API requests and responses to improve data retrieval efficiency.
  • Bug Fixes

    • Updated status indicators in README.md for better clarity on availability of "Persons" and "Opportunities."
  • Documentation

    • Expanded documentation for new types and methods in the Persons API, enhancing clarity for developers.
  • Refactor

    • Simplified type definitions and import structures across various modules for better maintainability.

Copy link

coderabbitai bot commented Jul 25, 2024

Walkthrough

This update enhances the codebase by introducing automatic draft reviews and refining pagination handling. Type definitions have been improved for clarity and safety, along with new utility types for flexible data structures. Documentation has been expanded, and testing has been bolstered to ensure robustness. Collectively, these changes streamline processes and improve API functionality, enhancing usability and maintainability.

Changes

Files Change Summary
.coderabbit.yaml Added reviews.auto_review.drafts: true for automatic draft reviews.
.yamlfmt, src/v1/paged_request.ts, src/v1/paged_response.ts Introduced eof_newline: true and new types for paginated API request and responses.
README.md Updated entity statuses: Persons from ❌ to ✅ and Opportunities from ✅ to ❌.
src/v1/auth.ts Introduced GrantRaw type and updated WhoAmIResponseRaw for improved type safety.
src/v1/create_search_iterator_fn.ts New generic function createSearchIteratorFn for handling paginated API responses.
src/v1/field_value_changes.ts, src/v1/field_values.ts Removed RequireOnlyOne type; introduced Replace in changed_at handling for better structure.
src/v1/index.ts Added persons property to Affinity class for managing person-related data.
src/v1/list_entries.ts Enhanced ListEntryResponse; removed transformEntry, using transformListEntryReference.
src/v1/organizations.ts Introduced new types for opportunities and interaction dates; refactored searchIterator.
src/v1/persons.ts Expanded Person API with new types and improved internal interactions.
src/v1/tests/fixtures/persons/*.json New JSON files for structured responses reflecting person data and pagination.
src/v1/tests/persons_test.ts New test suite for Affinity class focusing on persons methods.
src/v1/transform_interaction_date_response_raw.ts, src/v1/transform_list_entry_reference.ts New functions for transforming interaction dates and list entry references.
src/v1/types.ts Added Replace and RequireOnlyOne types for enhanced type manipulation.
src/v1/urls.ts Added personsUrl and personFieldsUrl functions for constructing person-related URLs.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant API
    participant DraftReviewSystem
    participant Paginator

    User->>API: Submit draft
    API->>DraftReviewSystem: Review draft automatically
    DraftReviewSystem-->>API: Return review results
    API-->>User: Send response with review results

    User->>API: Request paginated data
    API->>Paginator: Fetch data with page token
    Paginator-->>API: Return paginated response
    API-->>User: Send paginated data response
Loading

🐰 In a world of code so bright,
With changes made, all feels right.
Drafts now reviewed without a fuss,
Pagination brings data to us.
A hop, a skip, through JSON we play,
Improvements abound, hip-hip-hooray! 🎉


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 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.

@joscha
Copy link
Member Author

joscha commented Jul 25, 2024

@coderabbitai review

Copy link

coderabbitai bot commented Jul 25, 2024

Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

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

Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 7ef2976 and e468838.

Files ignored due to path filters (1)
  • src/v1/tests/__snapshots__/persons_test.ts.snap is excluded by !**/*.snap
Files selected for processing (21)
  • .coderabbit.yaml (1 hunks)
  • .yamlfmt (1 hunks)
  • README.md (1 hunks)
  • src/v1/auth.ts (3 hunks)
  • src/v1/create_search_iterator_fn.ts (1 hunks)
  • src/v1/field_value_changes.ts (2 hunks)
  • src/v1/field_values.ts (2 hunks)
  • src/v1/index.ts (3 hunks)
  • src/v1/list_entries.ts (7 hunks)
  • src/v1/organizations.ts (12 hunks)
  • src/v1/paged_request.ts (1 hunks)
  • src/v1/paged_response.ts (1 hunks)
  • src/v1/persons.ts (2 hunks)
  • src/v1/tests/fixtures/persons/get.raw.response.json (1 hunks)
  • src/v1/tests/fixtures/persons/paginated.iterator.combined.response.json (1 hunks)
  • src/v1/tests/fixtures/persons/search.raw.response.json (1 hunks)
  • src/v1/tests/persons_test.ts (1 hunks)
  • src/v1/transform_interaction_date_response_raw.ts (1 hunks)
  • src/v1/transform_list_entry_reference.ts (1 hunks)
  • src/v1/types.ts (1 hunks)
  • src/v1/urls.ts (1 hunks)
Files skipped from review due to trivial changes (3)
  • src/v1/paged_response.ts
  • src/v1/tests/fixtures/persons/get.raw.response.json
  • src/v1/tests/fixtures/persons/search.raw.response.json
Additional comments not posted (52)
.coderabbit.yaml (1)

1-3: LGTM!

The configuration for enabling drafts in auto reviews is appropriate.

.yamlfmt (1)

2-2: LGTM!

The configuration for ensuring end-of-file newlines is beneficial for maintaining coding standards.

src/v1/transform_list_entry_reference.ts (1)

1-12: LGTM!

The function transformListEntryReference is correctly implemented using TypeScript generics and type assertions. The date transformation is handled appropriately.

src/v1/types.ts (2)

6-6: LGTM!

The Replace type definition is correct and effectively uses TypeScript's utility types.


11-17: LGTM!

The RequireOnlyOne type definition is complex but correct, leveraging advanced TypeScript features effectively.

src/v1/paged_request.ts (1)

3-16: LGTM!

The PagedRequest type definition is correct and effectively defines properties for pagination.

src/v1/transform_interaction_date_response_raw.ts (1)

14-41: LGTM!

The transformInteractionDateResponseRaw function is correct and effectively transforms the raw interaction date responses.

src/v1/tests/fixtures/persons/paginated.iterator.combined.response.json (1)

1-51: JSON structure and data look good!

The JSON structure is correct and the data is appropriate for testing pagination.

src/v1/urls.ts (2)

74-76: URL construction logic looks good!

The personsUrl function correctly constructs URLs for accessing person resources.


82-82: Function is consistent with existing patterns.

The personFieldsUrl function is consistent with the existing pattern of URL construction functions.

src/v1/index.ts (2)

9-9: Import statement for Persons looks good.

The import statement is correctly added and consistent with the rest of the imports.


55-55: Addition and initialization of persons property look good.

The persons property is correctly added as a public readonly member and initialized in the constructor.

Also applies to: 72-72

src/v1/auth.ts (3)

5-5: Import statement for DateTime and Replace looks good.

The import statement is correctly added and consistent with the rest of the imports.


40-43: Addition of GrantRaw type looks good.

The GrantRaw type is correctly added to encapsulate properties of the grant object and follows best practices.


46-46: Modifications to WhoAmIResponseRaw and WhoAmIResponse types look good.

The type modifications are correctly applied and follow best practices.

Also applies to: 58-59, 61-67

README.md (2)

35-35: Status change of Persons entity looks good.

The status change from ❌ to ✅ correctly reflects the current state of the entity.


36-36: Status change of Opportunities entity looks good.

The status change from ✅ to ❌ correctly reflects the current state of the entity.

src/v1/tests/persons_test.ts (3)

36-44: LGTM! Verify the accuracy of mock data and snapshots.

The test case for searching persons is well-structured. Ensure that the mock data in persons/search.raw.response.json and the snapshot validation are accurate.

Verification successful

LGTM! The test case for searching persons is well-structured. The mock data and snapshot validation are accurate.

  • Mock Data: search.raw.response.json
  • Snapshot: persons_test.ts.snap
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the accuracy of mock data and snapshots.

# Test: Check the existence and content of the mock data file.
fd 'persons/search.raw.response.json' | xargs cat

# Test: Check the existence and content of the snapshot file.
fd 'snapshots/persons_test.ts' | xargs cat

Length of output: 92


Script:

#!/bin/bash
# Description: Verify the accuracy of mock data and snapshots.

# Test: Search for the mock data file and display its content if found.
fd 'search.raw.response.json' | xargs cat

# Test: Search for the snapshot file and display its content if found.
fd 'persons_test.ts.snap' | xargs cat

Length of output: 3892


111-155: LGTM! Verify the accuracy of mock data and snapshots.

The test case for iterating over all persons using pagination is well-structured. Ensure that the mock data in persons/paginated.iterator.combined.response.json and the snapshot validation are accurate.

Verification successful

LGTM! The mock data and snapshot files are accurate and relevant to the test case.

The test case for iterating over all persons using pagination is well-structured, and the mock data in src/v1/tests/fixtures/persons/paginated.iterator.combined.response.json is appropriate for the test. The snapshot validation in src/v1/tests/persons_test.ts is correctly implemented.

  • Mock data file: src/v1/tests/fixtures/persons/paginated.iterator.combined.response.json
  • Snapshot file: src/v1/tests/persons_test.ts
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the accuracy of mock data and snapshots.

# Test: Check the existence and content of the mock data file.
fd 'persons/paginated.iterator.combined.response.json' | xargs cat

# Test: Check the existence and content of the snapshot file.
fd 'snapshots/persons_test.ts' | xargs cat

Length of output: 109


Script:

#!/bin/bash
# Description: Verify the existence and content of the mock data and snapshots.

# Test: Check the existence and content of the mock data file.
mock_data_file=$(fd 'persons/paginated.iterator.combined.response.json')
if [ -n "$mock_data_file" ]; then
    echo "Mock data file found: $mock_data_file"
    cat "$mock_data_file"
else
    echo "Mock data file not found."
fi

# Test: Check the existence and content of the snapshot file.
snapshot_file=$(fd 'snapshots/persons_test.ts')
if [ -n "$snapshot_file" ]; then
    echo "Snapshot file found: $snapshot_file"
    cat "$snapshot_file"
else
    echo "Snapshot file not found."
fi

Length of output: 274


Script:

#!/bin/bash
# Description: Search for all JSON files and snapshot files in the repository.

# Search for all JSON files to locate the mock data file.
echo "Searching for all JSON files in the repository..."
fd --extension json

# Search for all snapshot files to locate the snapshot file.
echo "Searching for all snapshot files in the repository..."
fd --extension ts --exec grep -l 'assertSnapshot'

Length of output: 2537


Script:

#!/bin/bash
# Description: Display the content of the identified mock data and snapshot files.

# Display the content of the mock data file.
echo "Content of the mock data file:"
cat src/v1/tests/fixtures/persons/paginated.iterator.combined.response.json

# Display the content of the snapshot file.
echo "Content of the snapshot file:"
cat src/v1/tests/persons_test.ts

Length of output: 6687


26-34: LGTM! Verify the accuracy of mock data and snapshots.

The test case for fetching a specific person is well-structured. Ensure that the mock data in persons/get.raw.response.json and the snapshot validation are accurate.

Verification successful

LGTM! The mock data and snapshot validation are accurate.

The test case for fetching a specific person is well-structured, and the mock data in persons/get.raw.response.json and the snapshot validation in __snapshots__/persons_test.ts.snap are consistent and correct.

  • Mock data file: src/v1/tests/fixtures/persons/get.raw.response.json
  • Snapshot file: src/v1/tests/__snapshots__/persons_test.ts.snap
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the accuracy of mock data and snapshots.

# Test: Check the existence and content of the mock data file.
fd 'persons/get.raw.response.json' | xargs cat

# Test: Check the existence and content of the snapshot file.
fd 'snapshots/persons_test.ts' | xargs cat

Length of output: 89


Script:

#!/bin/bash
# Description: Verify the existence and content of mock data and snapshot files with more context.

# Search for the mock data file and print its path if found.
fd 'get.raw.response.json' -a

# Search for the snapshot file and print its path if found.
fd 'persons_test.ts' -a

Length of output: 392


Script:

#!/bin/bash
# Description: Verify the content of mock data and snapshot files.

# Print the content of the mock data file.
cat /home/jailuser/git/src/v1/tests/fixtures/persons/get.raw.response.json

# Print the content of the snapshot file.
cat /home/jailuser/git/src/v1/tests/__snapshots__/persons_test.ts.snap

Length of output: 3400

src/v1/field_value_changes.ts (2)

82-84: LGTM! The type definition change improves type safety.

The updated FieldValueChange type definition using the Replace utility type is well-structured and improves type safety by replacing the changed_at property with a Date type.


Line range hint 74-81: LGTM! The type definition is correct.

The GetFieldValueChangesRequest type definition correctly uses the RequireOnlyOne utility type to enforce that only one of the specified properties can be present at a time.

src/v1/field_values.ts (2)

6-6: LGTM! The import change is correct.

The Replace type has been correctly added to the imports and is used in the updated type definitions.


158-165: LGTM! The type definition change improves type safety.

The updated FieldValue type definition using the Replace utility type is well-structured and improves type safety by replacing the updated_at and created_at properties with new types.

src/v1/list_entries.ts (5)

77-79: LGTM!

The transformation of created_at to a Date using the Replace type enhances type safety.


81-83: LGTM!

The transformation of list_entries to an array of ListEntryResponse using the Replace type ensures consistency.


208-212: LGTM!

The refactor to use transformListEntryReference simplifies the transformation process and ensures consistency.


241-241: LGTM!

The refactor to use transformListEntryReference simplifies the transformation process and ensures consistency.


338-338: LGTM!

The refactor to use transformListEntryReference simplifies the transformation process and ensures consistency.

src/v1/persons.ts (13)

42-67: LGTM!

The introduction of PersonResponseRaw enhances the data model and provides clarity.


69-69: LGTM!

The use of Replace type for incorporating InteractionDateResponse ensures a dynamic and context-aware representation of person data.


71-76: LGTM!

The expansion of WithCurrentOrganizatonParams adds flexibility to the API interactions.


78-91: LGTM!

The expansion of SearchPersonsRequest enhances the functionality of the search API.


93-97: LGTM!

The expansion of PagedPersonResponseRaw improves the structure of paginated responses.


99-101: LGTM!

The transformation of persons to an array of PersonResponse using the Replace type ensures consistency.


103-107: LGTM!

The expansion of SinglePersonResponseRaw improves the structure of single person responses.


109-116: LGTM!

The expansion of SinglePersonResponse improves the structure of single person responses.


118-122: LGTM!

The expansion of GetPersonRequest enhances the flexibility of the get person API.


124-127: LGTM!

The expansion of PersonReference improves the structure of person references.


168-194: LGTM!

The update to handle SinglePersonResponseRaw and transform it to SinglePersonResponse ensures that the response format aligns with the latest data models.


216-240: LGTM!

The update to handle PagedPersonResponseRaw and transform it to PagedPersonResponse ensures that the response format aligns with the latest data models.


261-261: LGTM!

The refactor to use createSearchIteratorFn simplifies the logic for iterating over search results.

src/v1/organizations.ts (10)

55-63: LGTM!

The introduction of OpportunityIdResponseRaw enhances the data model and provides clarity.


74-94: LGTM!

The update to include detailed interaction date information allows for more precise data modeling.


96-117: LGTM!

The update to include detailed interaction date information allows for more precise data modeling.


135-136: LGTM!

The expansion to include OpportunityIdResponseRaw and InteractionDateResponseRaw enhances the data model and provides clarity.


159-161: LGTM!

The transformation of date to a Date using the Replace type enhances type safety.


163-166: LGTM!

The use of Replace type for incorporating InteractionDateResponse ensures a dynamic and context-aware representation of organization data.


172-176: LGTM!

The expansion of PagedOrganizationResponseRaw improves the structure of paginated responses.


178-180: LGTM!

The transformation of organizations to an array of OrganizationResponse using the Replace type ensures consistency.


188-189: LGTM!

The expansion of SingleOrganizationResponseRaw improves the structure of single organization responses.


191-195: LGTM!

The expansion of SingleOrganizationResponse improves the

@@ -0,0 +1,16 @@
// TODO(@joscha): see if we need to unify some of this with the `PagingParameters`.
Copy link

Choose a reason for hiding this comment

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

Reminder: Unify with PagingParameters.

The TODO comment indicates a potential future improvement to unify this with PagingParameters.

Do you want me to open a GitHub issue to track this task?

Comment on lines +4 to +39
export const createSearchIteratorFn = <
FN extends (r: PAGED_REQUEST) => Promise<PAGED_RESPONSE>,
PAGED_REQUEST extends PagedRequest,
PAGED_RESPONSE extends
& PagedResponse
& Record<PAYLOAD_KEY, SINGLE_RESPONSE[]>,
PAYLOAD_KEY extends string =
& keyof Omit<PAGED_RESPONSE, keyof PagedResponse>
& string,
SINGLE_RESPONSE = object,
>(searchFn: FN, key: PAYLOAD_KEY) => {
async function* searchIterator(
params: Omit<PAGED_REQUEST, 'page_token'>,
): AsyncGenerator<PAGED_RESPONSE[]> {
let page_token: string | undefined = undefined
while (true) {
const response: PAGED_RESPONSE = await searchFn(
// TODO(@joscha): remove cast
(page_token
? { ...params, page_token }
: params) as PAGED_REQUEST,
)

// TODO(@joscha): remove cast
yield response[key] as unknown as PAGED_RESPONSE[]

if (response.next_page_token === null) {
// no more pages to fetch
return
} else {
page_token = response.next_page_token
}
}
}
return searchIterator
}
Copy link

Choose a reason for hiding this comment

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

Consider removing TODO comments or addressing them.

There are TODO comments indicating casts that need to be removed. Ensure these are addressed before finalizing the code.

-    // TODO(@joscha): remove cast
-    (page_token
-        ? { ...params, page_token }
-        : params) as PAGED_REQUEST,
+    const requestParams: PAGED_REQUEST = page_token
+        ? { ...params, page_token }
+        : params;
+    const response: PAGED_RESPONSE = await searchFn(requestParams);
-    // TODO(@joscha): remove cast
-    yield response[key] as unknown as PAGED_RESPONSE[]
+    const responsePayload: PAGED_RESPONSE[] = response[key];
+    yield responsePayload;

Comment on lines 46 to 63
// it('can search for persons with the appropriate dates', async (t) => {
// const myDate = new Date(1717428411010)
// const request: SearchPersonsRequest = {
// min_first_email_date: myDate,
// term: 'joscha',
// }
// mock?.onGet(personsUrl(), {
// params: {
// term: request.term,
// min_first_email_date: myDate.toISOString(),
// },
// }).reply(
// 200,
// await getRawFixture('persons/search.raw.response.json'),
// )
// const res = await affinity.persons.search(request)
// await assertSnapshot(t, res)
// })
Copy link

Choose a reason for hiding this comment

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

Commented-out test case: Clarify the status.

The test case for searching persons with the appropriate dates is commented out. Is this test case incomplete or under development? Do you need assistance in completing it?

Comment on lines 65 to 77
// it('can create a new person', async (t) => {
// const data = {
// name: 'Acme Corporation',
// domain: 'acme.co',
// person_ids: [38706],
// }
// mock?.onPost(personsUrl()).reply(
// 201,
// await getRawFixture('persons/create.raw.response.json'),
// )
// const res = await affinity.persons.create(data)
// await assertSnapshot(t, res)
// })
Copy link

Choose a reason for hiding this comment

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

Commented-out test case: Clarify the status.

The test case for creating a new person is commented out. Is this test case incomplete or under development? Do you need assistance in completing it?

Comment on lines 79 to 91
// it('can update a person', async (t) => {
// const data = {
// person_id: 120611418,
// name: 'Acme Corp.',
// person_ids: [38706, 89734],
// }
// mock?.onPut(personsUrl(data.person_id)).reply(
// 200,
// await getRawFixture('persons/update.raw.response.json'),
// )
// const res = await affinity.persons.update(data)
// await assertSnapshot(t, res)
// })
Copy link

Choose a reason for hiding this comment

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

Commented-out test case: Clarify the status.

The test case for updating a person is commented out. Is this test case incomplete or under development? Do you need assistance in completing it?

Comment on lines 93 to 100
// it('can delete a person', async (t) => {
// const person_id = 120611418
// mock?.onDelete(personsUrl(person_id)).reply(200, {
// success: true,
// })
// const res = await affinity.persons.delete({ person_id })
// await assertSnapshot(t, res)
// })
Copy link

Choose a reason for hiding this comment

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

Commented-out test case: Clarify the status.

The test case for deleting a person is commented out. Is this test case incomplete or under development? Do you need assistance in completing it?

Comment on lines 102 to 109
// it('can get global person fields', async (t) => {
// mock?.onGet(personFieldsUrl()).reply(
// 200,
// await getRawFixture('persons/get_fields.raw.response.json'),
// )
// const res = await affinity.persons.getFields()
// await assertSnapshot(t, res)
// })
Copy link

Choose a reason for hiding this comment

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

Commented-out test case: Clarify the status.

The test case for getting global person fields is commented out. Is this test case incomplete or under development? Do you need assistance in completing it?

Comment on lines +15 to +37
async function* searchIterator(
params: Omit<PAGED_REQUEST, 'page_token'>,
): AsyncGenerator<PAGED_RESPONSE[]> {
let page_token: string | undefined = undefined
while (true) {
const response: PAGED_RESPONSE = await searchFn(
// TODO(@joscha): remove cast
(page_token
? { ...params, page_token }
: params) as PAGED_REQUEST,
)

// TODO(@joscha): remove cast
yield response[key] as unknown as PAGED_RESPONSE[]

if (response.next_page_token === null) {
// no more pages to fetch
return
} else {
page_token = response.next_page_token
}
}
}
Copy link

Choose a reason for hiding this comment

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

Ensure proper error handling for the asynchronous generator.

The function does not handle potential errors from the searchFn call. Consider adding try-catch blocks to handle errors gracefully.

+    try {
        const response: PAGED_RESPONSE = await searchFn(
            // TODO(@joscha): remove cast
            (page_token
                ? { ...params, page_token }
                : params) as PAGED_REQUEST,
        )

        // TODO(@joscha): remove cast
        yield response[key] as unknown as PAGED_RESPONSE[]

        if (response.next_page_token === null) {
            // no more pages to fetch
            return
        } else {
            page_token = response.next_page_token
        }
+    } catch (error) {
+        console.error("Error fetching page:", error);
+        throw error;
+    }
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. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
async function* searchIterator(
params: Omit<PAGED_REQUEST, 'page_token'>,
): AsyncGenerator<PAGED_RESPONSE[]> {
let page_token: string | undefined = undefined
while (true) {
const response: PAGED_RESPONSE = await searchFn(
// TODO(@joscha): remove cast
(page_token
? { ...params, page_token }
: params) as PAGED_REQUEST,
)
// TODO(@joscha): remove cast
yield response[key] as unknown as PAGED_RESPONSE[]
if (response.next_page_token === null) {
// no more pages to fetch
return
} else {
page_token = response.next_page_token
}
}
}
async function* searchIterator(
params: Omit<PAGED_REQUEST, 'page_token'>,
): AsyncGenerator<PAGED_RESPONSE[]> {
let page_token: string | undefined = undefined
while (true) {
+ try {
const response: PAGED_RESPONSE = await searchFn(
// TODO(@joscha): remove cast
(page_token
? { ...params, page_token }
: params) as PAGED_REQUEST,
)
// TODO(@joscha): remove cast
yield response[key] as unknown as PAGED_RESPONSE[]
if (response.next_page_token === null) {
// no more pages to fetch
return
} else {
page_token = response.next_page_token
}
+ } catch (error) {
+ console.error("Error fetching page:", error);
+ throw error;
+ }
}
}

src/v1/field_value_changes.ts Show resolved Hide resolved
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

Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

Commits

Files that changed from the base of the PR and between e468838 and 00475a5.

Files ignored due to path filters (1)
  • src/v1/tests/__snapshots__/persons_test.ts.snap is excluded by !**/*.snap
Files selected for processing (9)
  • src/v1/organizations.ts (14 hunks)
  • src/v1/persons.ts (2 hunks)
  • src/v1/tests/fixtures/persons/create.raw.response.json (1 hunks)
  • src/v1/tests/fixtures/persons/get_fields.raw.response.json (1 hunks)
  • src/v1/tests/fixtures/persons/search_with_dates.raw.response.json (1 hunks)
  • src/v1/tests/fixtures/persons/update.raw.response.json (1 hunks)
  • src/v1/tests/organizations_test.ts (1 hunks)
  • src/v1/tests/persons_test.ts (1 hunks)
  • src/v1/transform_interaction_date_response_raw.ts (1 hunks)
Files skipped from review due to trivial changes (3)
  • src/v1/tests/fixtures/persons/create.raw.response.json
  • src/v1/tests/fixtures/persons/get_fields.raw.response.json
  • src/v1/tests/fixtures/persons/update.raw.response.json
Files skipped from review as they are similar to previous changes (1)
  • src/v1/tests/persons_test.ts
Additional comments not posted (39)
src/v1/tests/fixtures/persons/search_with_dates.raw.response.json (1)

1-30: JSON Structure Validation

The JSON structure appears to be well-formed and includes detailed information about a person, including interaction dates and interactions. Ensure that the data accurately reflects the expected schema and use cases.

src/v1/transform_interaction_date_response_raw.ts (2)

48-48: Reminder: Fix types to avoid casting.

The TODO comment indicates a potential improvement to fix the types and avoid casting.


14-49: Function Implementation Validation

The function transformInteractionDateResponseRaw processes raw interaction date responses and converts date strings to Date objects. The implementation appears to be correct.

src/v1/tests/organizations_test.ts (2)

51-51: New Property Addition Validation

The new property with_interaction_dates is correctly added to the SearchOrganizationsRequest object. Ensure that the test cases cover all necessary scenarios.


57-57: New Property Addition Validation

The new property with_interaction_dates is correctly added to the parameters of the mocked GET request. Ensure that the test cases cover all necessary scenarios.

src/v1/persons.ts (19)

73-73: LGTM!

The type PersonResponse correctly uses the Replace utility type.


75-80: LGTM!

The type WithCurrentOrganizatonParams is well-defined.


82-95: LGTM!

The type SearchPersonsRequest is well-defined and includes various query parameters.


97-105: LGTM!

The type PagedPersonResponseRaw is well-defined and includes an array of PersonResponseRaw.


109-112: LGTM!

The type SinglePersonResponseRaw is well-defined and includes list entries and PersonResponseRaw.


113-121: LGTM!

The type SinglePersonResponse correctly uses the Replace utility type.


123-127: LGTM!

The type GetPersonRequest is well-defined and includes various query parameters.


129-131: LGTM!

The type PersonReference is well-defined and includes the unique ID of the person.


136-153: LGTM!

The type CreatePersonRequest is well-defined and includes various fields for creating a person.


158-183: LGTM!

The type UpdatePersonRequest is well-defined and includes various fields for updating a person.


186-191: LGTM!

The type SimplePersonResponse is well-defined and includes the Person type and selected fields from PersonResponse.


232-259: LGTM!

The get method is well-implemented and handles the transformation of the response correctly.


280-305: LGTM!

The search method is well-implemented and handles the transformation of the response correctly.


325-328: LGTM!

The searchIterator method is well-implemented and uses the createSearchIteratorFn utility function correctly.


347-355: LGTM!

The create method is well-implemented and handles the creation of a person correctly.


373-382: LGTM!

The update method is well-implemented and handles the update of a person correctly.


396-402: LGTM!

The delete method is well-implemented and handles the deletion of a person correctly.


415-422: LGTM!

The getFields method is well-implemented and handles the fetching of person fields correctly.


60-71: Ensure the type system models the return type based on the query parameter type.

The TODO comment suggests modeling the return type based on the query parameter type.

-        current_organization_ids?: number[]
+        current_organization_ids?: number[] // TODO: Model this in the type system

Likely invalid or redundant comment.

src/v1/organizations.ts (15)

131-136: LGTM!

The type OrganizationResponseRaw is well-defined and includes various fields.


172-177: LGTM!

The type PagedOrganizationResponseRaw is well-defined and includes an array of OrganizationResponseRaw.


178-180: LGTM!

The type PagedOrganizationResponse correctly uses the Replace utility type.


189-195: LGTM!

The type SingleOrganizationResponseRaw is well-defined and includes list entries and OrganizationResponseRaw.


191-195: LGTM!

The type SingleOrganizationResponse correctly uses the Replace utility type.


168-170: LGTM!

The type ListEntryReference correctly uses the Replace utility type.


Line range hint 324-352:
LGTM!

The get method is well-implemented and handles the transformation of the response correctly.


Line range hint 378-399:
LGTM!

The search method is well-implemented and handles the transformation of the response correctly.


419-422: LGTM!

The searchIterator method is well-implemented and uses the createSearchIteratorFn utility function correctly.


Line range hint 460-471:
LGTM!

The create method is well-implemented and handles the creation of an organization correctly.


Line range hint 493-502:
LGTM!

The update method is well-implemented and handles the update of an organization correctly.


Line range hint 524-530:
LGTM!

The delete method is well-implemented and handles the deletion of an organization correctly.


Line range hint 548-555:
LGTM!

The getFields method is well-implemented and handles the fetching of organization fields correctly.


74-94: Ensure the type system models the return type based on the query parameter type.

The TODO comment suggests modeling the return type based on the query parameter type.

-    interaction_dates?: {
-        [key in InteractionDateKey]: DateTime
-    }
-    interactions?: {
-        [key in InteractionType]: InteractionDateRaw
-    }
+    interaction_dates?: {
+        [key in InteractionDateKey]: DateTime // TODO: Model this in the type system
+    }
+    interactions?: {
+        [key in InteractionType]: InteractionDateRaw // TODO: Model this in the type system
+    }

Likely invalid or redundant comment.


96-117: Ensure the type system models the return type based on the query parameter type.

The TODO comment suggests modeling the return type based on the query parameter type.

-    interaction_dates?: {
-        [key in InteractionDateKey]: Date
-    }
-    interactions?: {
-        [key in InteractionType]: InteractionDate
-    }
+    interaction_dates?: {
+        [key in InteractionDateKey]: Date // TODO: Model this in the type system
+    }
+    interactions?: {
+        [key in InteractionType]: InteractionDate // TODO: Model this in the type system
+    }

Likely invalid or redundant comment.

Comment on lines +55 to +63
export type OpportunityIdResponseRaw = {
/**
* An array of unique identifiers of opportunities ({@link Opportunity.id}) that are associated with the entity.
* Only returned when passing `{@link OpportunitiesQueryParams.with_opportunities}=true`.
*
* TODO(@joscha): model this in the type system, so the return type is based on the query parameter type.
*/
opportunity_ids?: number[]
}
Copy link

Choose a reason for hiding this comment

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

Ensure the type system models the return type based on the query parameter type.

The TODO comment suggests modeling the return type based on the query parameter type.

-    opportunity_ids?: number[]
+    opportunity_ids?: number[] // TODO: Model this in the type system

Committable suggestion was skipped due to low confidence.

@joscha joscha marked this pull request as ready for review July 26, 2024 08:48
@joscha joscha merged commit 54f63b7 into main Jul 26, 2024
8 checks passed
@joscha joscha deleted the joscha/persons-endpoint branch July 26, 2024 08:48
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.

1 participant