Skip to content
This repository was archived by the owner on Sep 24, 2025. It is now read-only.
This repository was archived by the owner on Sep 24, 2025. It is now read-only.

Refactor RPC handler to use maps for method-to-handler mapping #185

@coderabbitai

Description

@coderabbitai

Description

Currently, the RPC handler uses switch statements to route method names to appropriate handler functions. This approach works but could be improved for maintainability and scalability.

Proposed Solution

Refactor the RPC handler to use maps for mapping method names directly to handler functions. This would:

  1. Eliminate the need for switch statements when routing methods
  2. Provide O(1) lookup time for method resolution
  3. Make adding new methods easier (just add a new entry to the map)
  4. Improve code maintainability

Implementation Suggestion

// Define a type for handler functions
type RPCHandlerFunc func(c *fiber.Ctx, ownerID uint, req RPCRequest) error

// In RPCHandler struct, add maps for method routing
type RPCHandler struct {
    ProjectHandlers *ProjectHandlers
    TaskHandlers    *TaskHandlers
    
    // Maps for method routing
    projectMethods map[string]RPCHandlerFunc
    taskMethods    map[string]RPCHandlerFunc
}

// Initialize maps in constructor
func NewRPCHandler(projectHandlers *ProjectHandlers, taskHandlers *TaskHandlers) *RPCHandler {
    h := &RPCHandler{
        ProjectHandlers: projectHandlers,
        TaskHandlers:    taskHandlers,
        projectMethods:  make(map[string]RPCHandlerFunc),
        taskMethods:     make(map[string]RPCHandlerFunc),
    }
    
    // Register project methods
    h.projectMethods[ProjectCreate] = projectHandlers.Create
    h.projectMethods[ProjectGet] = projectHandlers.Get
    // ... register other methods
    
    // Register task methods
    h.taskMethods[TaskGet] = taskHandlers.Get
    // ... register other methods
    
    return h
}

// Simplify method handling
func (h *RPCHandler) handleProjectMethod(c *fiber.Ctx, req RPCRequest) error {
    handler, exists := h.projectMethods[req.Method]
    if !exists {
        return respondWithRPCError(c, fiber.StatusBadRequest, ErrMsgUnknownProjMethod, nil, req.ID)
    }
    return handler(c, ownerID, req)
}

This approach would make the code more maintainable and extensible.

Related to

PR #182: Implemented RPC model for projects and tasks

Requested by

@mojtaba-esk

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions