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

refactor(api_admin)!: use query instead of body #69

Merged
merged 3 commits into from
Sep 26, 2024
Merged

Conversation

kwaa
Copy link
Member

@kwaa kwaa commented Sep 26, 2024

Summary by CodeRabbit

  • New Features

    • Updated account creation and removal processes to accept parameters via URL query strings instead of JSON payloads.
    • Simplified API command examples in documentation to reflect the new query parameter format.
  • Bug Fixes

    • Improved error handling and response messages for account creation and removal functions to align with the new input method.
  • Documentation

    • Revised API documentation to provide updated examples for creating accounts using query parameters.

@kwaa kwaa added the enhancement New feature or request label Sep 26, 2024
@kwaa kwaa added this to the 0.3 [Strobe Nights] milestone Sep 26, 2024
Copy link
Contributor

coderabbitai bot commented Sep 26, 2024

Walkthrough

The changes involve a significant shift in how account-related data is processed within the API. The CreateRemoveAccount structure has been renamed and its handling updated to utilize query parameters instead of JSON payloads for account creation and removal requests. This adjustment is reflected across multiple files, including route handlers and documentation, indicating a unified approach to parameter handling. The modifications enhance clarity in the codebase and streamline the interaction with the API.

Changes

Files Change Summary
crates/api_admin/src/entities/create_remove_account.rs Renamed CreateRemoveAccount to CreateRemoveAccountQuery, updated derive attributes from ToSchema to IntoParams.
crates/api_admin/src/entities/mod.rs Updated public export from CreateRemoveAccount to CreateRemoveAccountQuery, keeping CreateRemoveAccountResult unchanged.
crates/api_admin/src/routes/create_account.rs Changed function parameter from Json<CreateRemoveAccount> to Query<CreateRemoveAccountQuery>.
crates/api_admin/src/routes/mod.rs Removed CreateRemoveAccount from OpenAPI schema components.
crates/api_admin/src/routes/remove_account.rs Changed function parameter from Json<CreateRemoveAccount> to Query<CreateRemoveAccountQuery>.
docs/src/admins/create-account.md Updated example command to use query parameters instead of JSON payload for API account creation.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant API
    participant Database

    Client->>API: POST /create-account?name=example.com&token=abc123
    API->>Database: Create account with name example.com
    Database-->>API: Account created
    API-->>Client: 201 Created
Loading
sequenceDiagram
    participant Client
    participant API
    participant Database

    Client->>API: POST /remove-account?name=example.com&token=abc123
    API->>Database: Remove account with name example.com
    Database-->>API: Account removed
    API-->>Client: 200 OK
Loading

Poem

🐇 In fields of code where bunnies play,
New paths emerge, bright as day.
With queries clear and names so bright,
We hop along, all feels just right!
A leap for change, a joyful cheer,
For every byte, we hold so dear! 🌼


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>, 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 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
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: 0

🧹 Outside diff range and nitpick comments (7)
crates/api_admin/src/entities/create_remove_account.rs (2)

4-5: LGTM: Struct changes align with query parameter usage.

The modifications to the struct are consistent with the PR objective:

  1. Changing #[derive(ToSchema)] to #[derive(IntoParams)] supports the use of query parameters.
  2. Renaming the struct to CreateRemoveAccountQuery clearly indicates its purpose.

These changes enhance code clarity and maintain the expected functionality.

Consider using separate structs for creating and removing accounts (e.g., CreateAccountQuery and RemoveAccountQuery) to improve code clarity and adhere to the Single Responsibility Principle. This change would make the code more maintainable and easier to understand.


Line range hint 1-15: Summary: Successful refactoring to use query parameters

The changes in this file effectively implement the PR objective of using query parameters instead of a JSON body for account-related operations. Key points:

  1. The import and derive attribute changes support the use of IntoParams for query parameter handling.
  2. The struct renaming enhances code clarity.

These modifications improve the API's adherence to RESTful practices and make the code more maintainable. The transition appears smooth and well-executed.

Consider splitting the CreateRemoveAccountQuery into separate structs for creation and removal operations in the future. This would further improve code organization and make it easier to add operation-specific fields if needed.

docs/src/admins/create-account.md (1)

24-24: LGTM! Consider simplifying the command.

The updated curl command correctly reflects the change from using a JSON body to query parameters, which aligns with the PR objective. This change makes the API usage more straightforward and consistent with RESTful practices.

Consider simplifying the command by removing the unnecessary echo calls:

NAME="example.com" curl -X POST "http://localhost:$HATSU_LISTEN_PORT/api/v0/admin/create-account?name=$NAME&token=$HATSU_ACCESS_TOKEN"

This change makes the command slightly more readable while maintaining the same functionality.

crates/api_admin/src/routes/create_account.rs (1)

30-30: LGTM: Function updated to use query parameters consistently.

The changes in the function signature and implementation correctly reflect the shift from JSON payload to query parameters. The user URL generation and account creation logic have been updated accordingly.

Consider updating the error message on line 40 to reference the query parameter instead of an account:

-        format!("The account already exists: {}", account.name),
+        format!("An account with the name '{}' already exists", query.name),

This change would make the error message more consistent with the new query parameter approach.

Also applies to: 33-33, 44-44

crates/api_admin/src/routes/remove_account.rs (2)

28-28: LGTM: Function updated consistently to use query parameters.

The changes in the function signature and body correctly implement the shift from JSON payload to query parameters. All references to payload.name have been appropriately replaced with query.name, and error messages have been updated accordingly.

Consider adding input validation for the query.name parameter to ensure it meets any required format or length constraints before processing the request. This can help prevent potential issues with invalid input early in the request handling process.

Example:

if !is_valid_account_name(&query.name) {
    return Err(AppError::new(
        format!("Invalid account name: {}", query.name),
        None,
        Some(StatusCode::BAD_REQUEST),
    ));
}

Also applies to: 31-31, 51-51, 53-53, 59-59


Line range hint 1-64: Implement actual account removal functionality.

While the changes to use query parameters instead of JSON payload have been implemented correctly, the core functionality of account removal is still not implemented. The function continues to return a "not implemented" response.

Consider the following steps to complete the implementation:

  1. Implement the actual account removal logic, replacing the TODO comment.
  2. Update the response to reflect the success or failure of the account removal process.
  3. Add appropriate logging for the account removal action.
  4. Consider implementing a confirmation step or a "dry run" option to prevent accidental account removals.
  5. Ensure that all associated data (posts, followers, etc.) are handled appropriately during account removal.

Example skeleton for account removal:

// Inside the Some(account) branch
let result = remove_account_data(&data.conn, &account).await?;
if result.is_success() {
    Ok((
        StatusCode::OK,
        Json(CreateRemoveAccountResult {
            name: query.name.clone(),
            message: format!("Successfully removed account: {}", query.name),
        }),
    ))
} else {
    Err(AppError::new(
        format!("Failed to remove account: {}", query.name),
        None,
        Some(StatusCode::INTERNAL_SERVER_ERROR),
    ))
}

Don't forget to remove the TODO comment once the implementation is complete.

Justfile (1)

75-75: Approve change with considerations

The modification aligns with the PR objective of using query parameters instead of the request body. However, there are some important considerations:

  1. Using POST with query parameters is unconventional. Consider changing the HTTP method to GET for consistency with RESTful practices, especially since the data is now in the URL.

  2. Passing the access token as a query parameter may pose a security risk. Query parameters are often logged in server logs and can appear in browser history. Consider using a header (e.g., Authorization) for the token instead.

  3. This change might affect API compatibility. Ensure that all clients are updated to use the new parameter passing method.

To address these concerns, consider the following changes:

-  curl -X POST "http://localhost:${HATSU_LISTEN_PORT}/api/v0/admin/{{method}}-account?name={{name}}&token=${HATSU_ACCESS_TOKEN}"
+  curl -X GET "http://localhost:${HATSU_LISTEN_PORT}/api/v0/admin/{{method}}-account?name={{name}}" \
+       -H "Authorization: Bearer ${HATSU_ACCESS_TOKEN}"

This suggestion uses GET (which is more appropriate for query parameters), moves the token to the Authorization header, and keeps the account name as a query parameter.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between dfbf4fb and b6fa882.

📒 Files selected for processing (7)
  • Justfile (1 hunks)
  • crates/api_admin/src/entities/create_remove_account.rs (1 hunks)
  • crates/api_admin/src/entities/mod.rs (1 hunks)
  • crates/api_admin/src/routes/create_account.rs (4 hunks)
  • crates/api_admin/src/routes/mod.rs (1 hunks)
  • crates/api_admin/src/routes/remove_account.rs (4 hunks)
  • docs/src/admins/create-account.md (1 hunks)
🔇 Additional comments (11)
crates/api_admin/src/entities/mod.rs (1)

5-5: Approve renaming to CreateRemoveAccountQuery with follow-up actions.

The renaming from CreateRemoveAccount to CreateRemoveAccountQuery aligns well with the PR objective of using queries instead of body parameters. This change enhances clarity and consistency in the API design.

However, this modification has some important implications:

  1. It's a breaking change that will affect any code directly using CreateRemoveAccount.
  2. The new name is consistent with BlockUrlQuery, suggesting a pattern for naming query structs.

To ensure all references are updated and to identify any potential issues, please run the following verification script:

This script will help identify any areas that might need attention due to this renaming.

crates/api_admin/src/entities/create_remove_account.rs (1)

2-2: LGTM: Import change aligns with query parameter usage.

The change from ToSchema to IntoParams is consistent with the PR objective of using query parameters instead of a JSON body. This modification supports the new approach for handling account-related data in the API.

crates/api_admin/src/routes/create_account.rs (3)

4-4: LGTM: Import changes align with new query parameter approach.

The changes in the imports correctly reflect the shift from using a JSON payload to query parameters for input handling.


11-11: LGTM: Entity import updated to reflect query parameter usage.

The change from CreateRemoveAccount to CreateRemoveAccountQuery accurately represents the new approach of using query parameters for input.


20-20: LGTM: API documentation updated to reflect query parameter usage.

The params attribute in the API documentation has been correctly updated to use CreateRemoveAccountQuery, ensuring consistency with the new input method.

crates/api_admin/src/routes/mod.rs (3)

Line range hint 47-73: Changes are consistent with existing auth and routing logic.

The removal of CreateRemoveAccount and the corresponding OpenAPI schema changes are consistent with the existing authentication middleware and route definitions:

  1. The auth middleware still correctly checks for a token in query parameters, which aligns with the new approach of using query parameters for account operations.
  2. The route definitions remain unchanged, indicating that the API structure is maintained while only the internal handling of account operations has been modified.
  3. The security scheme definition is appropriately left unchanged, as the authentication method remains the same.

These observations confirm that the changes have been implemented consistently throughout the file.


Line range hint 25-29: OpenAPI schema components updated to reflect API changes.

The removal of CreateRemoveAccount from the OpenAPI schema components is consistent with the changes in the import statement and the PR objective. This update ensures that the API documentation accurately reflects the new approach of using query parameters for account operations.

Let's verify that the routes for create_account and remove_account are still present and haven't been accidentally removed:

#!/bin/bash
# Description: Verify that create_account and remove_account routes are still present

# Test: Search for create_account and remove_account route definitions. Expect: Both routes should be present.
rg --type rust "routes!\(create_account::create_account\)" crates/api_admin/src/routes/mod.rs
rg --type rust "routes!\(remove_account::remove_account\)" crates/api_admin/src/routes/mod.rs

16-16: Removal of CreateRemoveAccount import aligns with PR objective.

The removal of CreateRemoveAccount from the imports is consistent with the PR objective of using query parameters instead of request body for account operations. This change suggests that the structure is no longer needed for processing account creation and removal requests.

Let's verify that CreateRemoveAccount is not used elsewhere in the codebase:

✅ Verification successful

CreateRemoveAccount has been successfully removed from the codebase.

The CreateRemoveAccount entity is no longer present or used elsewhere, confirming that the removal aligns with the PR objective of handling account operations via query parameters.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for any remaining usage of CreateRemoveAccount in the codebase

# Test: Search for CreateRemoveAccount usage. Expect: No results.
rg --type rust "CreateRemoveAccount"

Length of output: 305

crates/api_admin/src/routes/remove_account.rs (3)

2-2: LGTM: Import changes align with new query parameter approach.

The changes in the imports correctly reflect the shift from using JSON payload to query parameters for the remove_account function.


8-8: LGTM: Entity import updated to reflect query-based approach.

The renaming of CreateRemoveAccount to CreateRemoveAccountQuery accurately represents the new query-based structure for account removal requests.


17-17: LGTM: API documentation updated to reflect query parameters.

The params attribute in the API documentation has been correctly updated to use CreateRemoveAccountQuery, ensuring consistency with the new query-based approach.

@kwaa kwaa merged commit 0911e39 into main Sep 26, 2024
2 checks passed
@kwaa kwaa deleted the refactor/api_admin branch September 26, 2024 16:17
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant