Skip to content

Comments

Iter2: Improvements#3

Open
mihailtudos wants to merge 4 commits intomasterfrom
Iter2
Open

Iter2: Improvements#3
mihailtudos wants to merge 4 commits intomasterfrom
Iter2

Conversation

@mihailtudos
Copy link
Owner

@mihailtudos mihailtudos commented Oct 3, 2024

Summary by CodeRabbit

  • New Features

    • Enhanced visibility of authentication and user handling structures, improving code organization.
  • Bug Fixes

    • Corrected naming inconsistencies in the authentication handler.
  • Refactor

    • Renamed various structs and methods to follow naming conventions and improve clarity.
    • Removed the orderService implementation, streamlining order management.
    • Updated timeout constants for order updates and server shutdown, enhancing maintainability.
    • Simplified order update logging by removing unnecessary console output.
  • Chores

    • Updated logger initialization method for improved clarity and consistency.

@coderabbitai
Copy link

coderabbitai bot commented Oct 3, 2024

Walkthrough

The changes in this pull request involve multiple modifications across several files, primarily focusing on renaming types and functions to adhere to Go's naming conventions, as well as altering the logger initialization method. The control flow in the Run function has been adjusted to change the order of operations during service initialization. Additionally, an orderService implementation has been removed entirely from the codebase.

Changes

File Path Change Summary
internal/app/api.go Updated logger initialization from Init to New. Changed timeout values to constants for readability.
internal/delivery/auth.go Renamed authHandler to AuthHandler and updated related constructor and method receivers.
internal/delivery/user.go Renamed userHandler to UserHandler and updated related methods and constructor.
internal/logger/logger.go Renamed Init function to New for logger initialization.
internal/repository/postgres/user.go Renamed userRepository to UserRepository and updated all associated methods to reflect the new name.
internal/service/service.go Removed loop in updateOrders method; added comments for future batch update implementation.
internal/service/order.go Removed orderService struct, its constructor NewOrderService, and the Create method.

Poem

In the code where rabbits play,
Names have changed, in a tidy way.
From Init to New, we hop along,
With AuthHandler, we sing our song.
The order service has said goodbye,
As we leap to new heights, oh my! 🐇✨


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.

@mihailtudos mihailtudos changed the title Iter2: Improvments Iter2: Improvements Oct 3, 2024
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Outside diff range and nitpick comments (8)
internal/logger/logger.go (2)

19-19: Update package documentation to reflect the new function name.

Since the main initialization function has been renamed, it's important to update the package documentation to reflect this change. This will help maintain clear and accurate documentation for users of the package.

Consider adding or updating the package documentation at the top of the file:

// Package logger provides a simple logging interface.
// Use New() to initialize the logger before use.
package logger

Line range hint 1-1: Fix typo in PR title

The PR title contains a typo: "Improvments" should be "Improvements".

Please update the PR title to "Iter2: Improvements" for clarity and correctness in commit history and changelogs.

internal/app/api.go (3)

25-25: LGTM! Consider adding error handling.

The change from logger.Init to logger.New looks good and likely reflects an update in the logger package's API. This change adopts a more idiomatic Go approach for initialization.

Consider adding error handling for the logger.New call, as initialization functions often return an error that should be checked:

-logger.New(nil, cfg.Logger.Level)
+if err := logger.New(nil, cfg.Logger.Level); err != nil {
+    return fmt.Errorf("failed to initialize logger: %w", err)
+}

Line range hint 58-66: Potential issue: Background process started before error check

The current implementation starts the background process (UpdateOrdersInBackground) before checking if the service initialization was successful. This could lead to unexpected behavior if the service initialization fails.

Consider moving the background process initiation after the error check:

ss, err := service.NewServices(userService, tms, accrualClient)

-// starting the backgorun process
-ss.UpdateOrdersInBackground(ctx, 1*time.Second)

if err != nil {
    logger.Log.ErrorContext(ctx,
        "failed to init services",
        slog.String("err", err.Error()))
    return err
}

+// starting the background process
+ss.UpdateOrdersInBackground(ctx, 1*time.Second)

This ensures that the background process is only started if the service initialization is successful.


Line range hint 22-110: Consider refactoring for improved code structure

The Run function is quite long and handles multiple responsibilities. Consider refactoring it to improve readability and maintainability:

  1. Extract initialization logic into separate functions (e.g., initLogger, initRepository, initServices).
  2. Standardize error handling to reduce repetition.
  3. Consider using a struct to hold all the components (logger, repository, services, server) and methods to initialize them.

Here's a high-level example of how you might refactor:

type App struct {
    cfg    *config.Config
    logger *slog.Logger
    repo   *repository.Repository
    services *service.Services
    server *server.Server
}

func NewApp() (*App, error) {
    app := &App{
        cfg: config.NewConfig(),
    }
    if err := app.initLogger(); err != nil {
        return nil, err
    }
    if err := app.initRepository(); err != nil {
        return nil, err
    }
    if err := app.initServices(); err != nil {
        return nil, err
    }
    if err := app.initServer(); err != nil {
        return nil, err
    }
    return app, nil
}

func (a *App) Run() error {
    // Server running logic
    // Graceful shutdown logic
}

// Add methods like initLogger, initRepository, etc.

This structure separates concerns and makes the code more modular and easier to test.

internal/delivery/user.go (2)

45-45: LGTM with a minor suggestion

The change to use UserHandler as the receiver is consistent with the struct renaming. The method's logic remains unchanged, which is good.

As a minor improvement, consider using a constant for the "Content-Type" header name to improve maintainability. You're already using a constant for the content type value (PlainTextContentType), so it would be consistent to do the same for the header name.

Consider applying this change:

-	if r.Header.Get(ContentTypeHeaderName) != PlainTextContentType {
+	if r.Header.Get("Content-Type") != PlainTextContentType {

This assumes you'll remove the ContentTypeHeaderName constant if it's not used elsewhere in the codebase.


94-94: LGTM with suggestion to remove debug statements

The change to use UserHandler as the receiver is consistent with the struct renaming. The method's logic remains unchanged, which is good.

However, there are some debug print statements in the method that might not be necessary in production code:

fmt.Printf("%#v", orders)
fmt.Println("order cOunt", len(orders))

Consider removing these debug print statements before merging this PR, unless they serve a specific purpose in your development or logging strategy.

internal/repository/postgres/user.go (1)

17-19: LGTM! Consider documenting the exported struct.

The renaming of userRepository to UserRepository makes the struct public, which is consistent with Go naming conventions for exported types. This change may impact the package's API, potentially allowing external packages to directly instantiate UserRepository.

Consider adding a comment to document the UserRepository struct, explaining its purpose and any important details about its usage, as it's now part of the public API.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 82699d2 and 9253fb5.

📒 Files selected for processing (6)
  • internal/app/api.go (1 hunks)
  • internal/delivery/auth.go (2 hunks)
  • internal/delivery/user.go (6 hunks)
  • internal/logger/logger.go (1 hunks)
  • internal/repository/postgres/user.go (11 hunks)
  • internal/service/order.go (0 hunks)
💤 Files with no reviewable changes (1)
  • internal/service/order.go
🧰 Additional context used
🪛 golangci-lint
internal/delivery/user.go

[error] 27-27: undefined: chi

(typecheck)

🔇 Additional comments (22)
internal/logger/logger.go (1)

19-19: Approve renaming Init to New, but verify impact on external code.

The renaming from Init to New aligns better with Go conventions for constructor-like functions. This is a good improvement in terms of idiomatic Go code.

However, this is a breaking change for any external code that was calling logger.Init(). Please run the following script to check for any usage of the old Init function in the codebase:

✅ Verification successful

Renaming Init to New verified and approved.

The renaming aligns with Go conventions, and no usages of logger.Init were found in the codebase, ensuring that the change is safe.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for usage of the old `Init` function in the codebase

# Test: Search for logger.Init usage
echo "Searching for logger.Init usage:"
rg --type go 'logger\.Init\('

# If no results are found, it's likely that the change is safe
if [ $? -ne 0 ]; then
    echo "No usage of logger.Init found. The renaming appears to be safe."
else
    echo "Usage of logger.Init found. Please update these calls to use logger.New instead."
fi

Length of output: 261

internal/delivery/auth.go (3)

30-30: Approve method receiver updates.

The method receivers for Signin and Signup have been correctly updated to use *AuthHandler, which is consistent with the struct renaming. The functionality of these methods remains unchanged, which is appropriate.

Also applies to: 89-89


26-27: ⚠️ Potential issue

Fix typo in function name and approve return type change.

The return type has been correctly updated to *AuthHandler, which is consistent with the struct renaming. However, there's a typo in the function name that needs to be addressed.

Please apply the following change:

-func NewAuthHanler(auth Auth) *AuthHandler {
+func NewAuthHandler(auth Auth) *AuthHandler {
 	return &AuthHandler{auth}
}

After fixing the typo, run this script to ensure the function is correctly referenced throughout the codebase:

#!/bin/bash
# Description: Check for correct usage of 'NewAuthHandler'

# Test: Search for 'NewAuthHandler' in all Go files. Expect: Only correct usages.
rg --type go 'NewAuthHandler'

Line range hint 1-150: Overall improvements and suggestions for further enhancements.

The changes in this file improve the code structure by following Go naming conventions for exported types. However, there are a few additional points to consider:

  1. The PR title contains a typo ("Improvments"). Consider updating it to "Iter2: Improvements" for better clarity.

  2. While the naming has been improved, there might be other areas for enhancement:

    • Consider adding comments to explain the purpose of the AuthHandler struct and its methods.
    • The error handling could potentially be refactored to reduce repetition.
    • The Signin and Signup methods are quite long. Consider breaking them down into smaller, more focused functions.
  3. Ensure that all references to the renamed types have been updated throughout the codebase.

Would you like assistance in implementing any of these suggestions?

To ensure comprehensive test coverage for the authentication functionality, run the following script:

#!/bin/bash
# Description: Check test coverage for auth-related code

# Test: Search for auth-related test files. Expect: Comprehensive test coverage.
fd -e go test auth
internal/delivery/user.go (5)

129-129: LGTM

The change to use UserHandler as the receiver is consistent with the struct renaming. The method's logic remains unchanged and appears to be implemented correctly.


Line range hint 1-191: Summary of changes and recommendations

Overall, the changes in this file look good. The main change was renaming userHandler to UserHandler, making it an exported type. This change is consistently applied throughout the file.

Here's a summary of the main points to address:

  1. Verify the intention behind exporting UserHandler and consider any potential impact on the package's API.
  2. Check the chi package import and ensure it's correctly set up in the project dependencies.
  3. Consider using a constant for the "Content-Type" header name in the registerOrder method.
  4. Remove debug print statements in the getOrders method if they're not needed in production.
  5. Fix the typo in the withrawalPoints method name (should be withdrawalPoints).

After addressing these points, the code will be in good shape for merging.

🧰 Tools
🪛 golangci-lint

[error] 27-27: undefined: chi

(typecheck)


[error] 30-30: undefined: chi

(typecheck)


144-144: ⚠️ Potential issue

LGTM with a typo correction

The change to use UserHandler as the receiver is consistent with the struct renaming. The method's logic remains unchanged and appears to be implemented correctly.

However, there's a typo in the method name: "withrawal" instead of "withdrawal".

Please correct the typo in the method name. Here's the suggested change:

-func (uh *UserHandler) withrawalPoints(w http.ResponseWriter, r *http.Request) {
+func (uh *UserHandler) withdrawalPoints(w http.ResponseWriter, r *http.Request) {

Don't forget to update any calls to this method elsewhere in the codebase.

To help identify any places where this method is called, you can run:

#!/bin/bash
# Search for calls to 'withrawalPoints'
rg --type go 'withrawalPoints'

This will help ensure that all occurrences of the misspelled method name are updated.


28-28: Verify chi import and usage

The change to use UserHandler is consistent with the struct renaming. However, there's a static analysis hint about an undefined chi at line 27. This could indicate a missing or incorrect import.

Please check the following:

  1. Ensure that the chi package is properly imported at the top of the file.
  2. Verify that the chi package is installed and available in your project's dependencies.

To help verify the chi import and usage, you can run the following command:

#!/bin/bash
# Check for chi import and usage
rg --type go 'import.*"github.com/go-chi/chi/v5"'
rg --type go 'chi\.NewMux\(\)'

This will help identify if the chi package is properly imported and used in the codebase.


23-23: Verify the intention behind exporting UserHandler

The struct has been changed from userHandler to UserHandler, making it exported. While this allows external packages to use this struct directly, it also changes the public API of the package.

Please confirm if this change is intentional and consider the following:

  1. Does this change align with the package's design and intended usage?
  2. Are there any external packages or code that might break due to this change?
  3. Do you need to update any documentation or tests to reflect this change?

To help verify the impact of this change, you can run the following command to find any usages of userHandler in the codebase:

This will help identify any places where the old unexported version was used and might need updating.

✅ Verification successful

Exporting UserHandler Verified Successfully

The renaming of userHandler to UserHandler has been consistently applied across the codebase, ensuring that the public API remains intact and no existing references are broken.

  • No remaining usages of userHandler were found in the codebase.
  • All references have been updated to use the exported UserHandler.

Note: A potential typo was identified in withrawalPoints. Please review and correct it to withdrawalPoints if necessary.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for usages of 'userHandler' in the codebase
rg --type go 'userHandler'

Length of output: 307


Script:

#!/bin/bash
# Corrected: Search for usages of 'userHandler' in the codebase
rg --type go 'userHandler'

Length of output: 26


Script:

#!/bin/bash
# Search for usages of 'UserHandler' in the codebase
rg --type go 'UserHandler'

# Search for potential typos of 'withdrawalPoints'
rg --type go 'withrawalPoints'

Length of output: 1009

internal/repository/postgres/user.go (13)

21-25: LGTM! Function signature updated correctly.

The NewUserRepository function signature has been correctly updated to return *UserRepository, which is consistent with the struct renaming. The function's logic remains unchanged, maintaining its current behavior.


28-28: LGTM! Method receiver updated correctly.

The Create method's receiver has been correctly updated to *UserRepository, which is consistent with the struct renaming. The method's logic and signature (apart from the receiver) remain unchanged.


63-63: LGTM! Method receiver updated correctly.

The SetSessionToken method's receiver has been correctly updated to *UserRepository, which is consistent with the struct renaming. The method's logic and signature (apart from the receiver) remain unchanged.


77-77: LGTM! Method receiver updated correctly.

The GetUserByLogin method's receiver has been correctly updated to *UserRepository, which is consistent with the struct renaming. The method's logic and signature (apart from the receiver) remain unchanged.


104-104: LGTM! Method receiver updated correctly.

The GetUserByID method's receiver has been correctly updated to *UserRepository, which is consistent with the struct renaming. The method's logic and signature (apart from the receiver) remain unchanged.


127-127: LGTM! Method receiver updated correctly.

The RegisterOrder method's receiver has been correctly updated to *UserRepository, which is consistent with the struct renaming. The method's logic and signature (apart from the receiver) remain unchanged.


184-184: LGTM! Method receiver updated correctly.

The GetUserOrders method's receiver has been correctly updated to *UserRepository, which is consistent with the struct renaming. The method's logic and signature (apart from the receiver) remain unchanged.


220-222: LGTM! Method receiver updated correctly.

The GetUserBalance method's receiver has been correctly updated to *UserRepository, which is consistent with the struct renaming. The method's logic and signature (apart from the receiver) remain unchanged.


224-224: LGTM! Method receiver updated correctly.

The WithdrawalPoints method's receiver has been correctly updated to *UserRepository, which is consistent with the struct renaming. The method's logic and signature (apart from the receiver) remain unchanged.


275-275: LGTM! Method receiver updated correctly.

The getUserBalance method's receiver has been correctly updated to *UserRepository, which is consistent with the struct renaming. The method's logic, signature (apart from the receiver), and visibility (unexported) remain unchanged.


289-289: LGTM! Method receiver updated correctly.

The GetWithdrawals method's receiver has been correctly updated to *UserRepository, which is consistent with the struct renaming. The method's logic and signature (apart from the receiver) remain unchanged.


326-326: LGTM! Method receivers updated correctly for both methods.

The GetUnfinishedOrders and UpdateOrder methods' receivers have been correctly updated to *UserRepository, which is consistent with the struct renaming. The methods' logic and signatures (apart from the receivers) remain unchanged.

Also applies to: 373-373


Line range hint 1-424: Overall changes look good, but consider adding documentation.

The changes in this file consistently rename userRepository to UserRepository, making the struct and its methods public. This change aligns with Go naming conventions for exported types. However, it's important to note that this change could impact the package's API by allowing external packages to directly instantiate and use UserRepository.

Consider adding documentation comments for the UserRepository struct and its public methods to provide clear usage guidelines for users of this package.

To ensure all occurrences of userRepository have been updated, run the following command:

If this command returns any results, it indicates that some occurrences of userRepository may have been missed in the renaming process.

✅ Verification successful

Renaming Verified Successfully.

All instances of userRepository have been successfully renamed to UserRepository. No remaining references were found.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for any remaining instances of "userRepository"
rg --type go 'userRepository' .

Length of output: 31


Script:

#!/bin/bash
# Comprehensive search for any remaining instances of "userRepository" in Go files, including comments and strings
rg --type go --ignore-case --multiline 'userRepository' .

Length of output: 2021

Comment on lines +22 to 23
type AuthHandler struct {
Auth
Copy link

Choose a reason for hiding this comment

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

💡 Codebase verification

Incomplete renaming of authHandler detected.

The struct authHandler has been renamed to AuthHandler, but the following references still use authHandler:

  • internal/delivery/handler.go
    • authHandler := NewAuthHanler(h.Auth)
    • r.Post("/login", authHandler.Signin)
    • r.Post("/register", authHandler.Signup)

Please update these instances to AuthHandler to ensure consistency and prevent potential issues.

🔗 Analysis chain

Approve the struct renaming and verify its impact.

The renaming of authHandler to AuthHandler follows Go's naming convention for exported types. This is a good improvement for consistency and potential reusability.

To ensure this change doesn't break any existing code, please run the following script to check for any remaining references to the old name:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for any remaining references to 'authHandler'

# Test: Search for 'authHandler' in all Go files. Expect: No results.
rg --type go 'authHandler'

Length of output: 206


Script:

#!/bin/bash
# Description: Check for any remaining references to 'authHandler' in Go files

# Test: Search for 'authHandler' in all Go files. Expect: No results.
rg --type go 'authHandler'

Length of output: 232

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Outside diff range and nitpick comments (1)
internal/service/service.go (1)

Line range hint 67-124: Consider implementing rate limiting for AccrualClient calls

While updating the orders, it's important to ensure that we're not overwhelming the AccrualClient with too many requests in a short period.

Consider implementing a rate limiter for AccrualClient calls. This could be done using a token bucket algorithm or a simple time-based limiter. Here's a simple example using time.Sleep:

import "golang.org/x/time/rate"

var limiter = rate.NewLimiter(rate.Every(time.Second), 10) // 10 requests per second

func (ss *Services) updateOrders(ctx context.Context) {
    // ... existing code ...

    for _, order := range orders {
        if err := limiter.Wait(ctx); err != nil {
            logger.Log.Error("rate limit exceeded", slog.String("err", err.Error()))
            return
        }

        updateOrder, err := ss.AccrualClient.GetOrderInfo(ctx, order)
        // ... rest of the code ...
    }
}

This ensures that we're not sending more than 10 requests per second to the AccrualClient. Adjust the rate as needed based on the AccrualClient's requirements.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 95baf8c and e16ad93.

📒 Files selected for processing (2)
  • internal/app/api.go (3 hunks)
  • internal/service/service.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • internal/app/api.go
🔇 Additional comments (1)
internal/service/service.go (1)

Line range hint 67-124: Removal of unnecessary console output is approved

The removal of the loop that printed order numbers and statuses is a good change. It reduces unnecessary console output, which is particularly beneficial in production environments.

The code is now cleaner and more suitable for production use. Good job on removing debug prints!

Comment on lines +108 to +109
// TODO: Batch update
// TODO: Batch update background
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider implementing batch updates for improved efficiency

The TODO comments suggest plans for batch updates. This is a good direction for optimization, especially if dealing with a large number of orders.

Consider implementing a batch update mechanism. This could involve:

  1. Grouping orders by status.
  2. Sending batch requests to the AccrualClient.
  3. Processing responses in bulk.

Here's a conceptual example of how you might start this refactoring:

func (ss *Services) updateOrders(ctx context.Context) {
    orders, err := ss.UserService.GetUnfinishedOrders(ctx)
    if err != nil {
        logger.Log.Error("update orders: get unfinished orders", slog.String("err", err.Error()))
        return
    }

    if len(orders) == 0 {
        return
    }

    // Group orders by status
    ordersByStatus := make(map[string][]domain.Order)
    for _, order := range orders {
        ordersByStatus[order.OrderStatus] = append(ordersByStatus[order.OrderStatus], order)
    }

    // Process each status group
    for status, ordersGroup := range ordersByStatus {
        // TODO: Implement batch request to AccrualClient
        // updatedOrders, err := ss.AccrualClient.GetOrdersInfoBatch(ctx, ordersGroup)
        
        // TODO: Process batch response and update orders
        // for _, updatedOrder := range updatedOrders {
        //     err := ss.UserService.UpdateOrder(ctx, updatedOrder)
        //     if err != nil {
        //         logger.Log.Error("failed to update the order status", slog.String("err", err.Error()))
        //     }
        // }
    }
}

This approach would require modifications to the AccrualClient interface to support batch operations.

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