veza/veza-backend-api/internal/handlers/search_handlers.go

83 lines
2.2 KiB
Go
Raw Normal View History

2025-12-03 19:29:37 +00:00
package handlers
import (
"net/http"
"strconv"
2025-12-03 19:29:37 +00:00
2026-03-06 18:13:16 +00:00
apperrors "veza-backend-api/internal/errors"
"veza-backend-api/internal/services"
2025-12-03 19:29:37 +00:00
"github.com/gin-gonic/gin"
)
var SearchHandlersInstance *SearchHandlers
// SearchServiceInterface defines the interface for search operations
// This allows for easier testing with mocks
type SearchServiceInterface interface {
Search(query string, types []string) (*services.SearchResult, error)
Suggestions(query string, limit int) (*services.SearchResult, error)
}
2025-12-03 19:29:37 +00:00
type SearchHandlers struct {
searchService SearchServiceInterface
2025-12-03 19:29:37 +00:00
}
func NewSearchHandlers(searchService *services.SearchService) {
SearchHandlersInstance = &SearchHandlers{
searchService: searchService,
}
}
// NewSearchHandlersWithInterface creates new search handlers with an interface (for testing)
func NewSearchHandlersWithInterface(searchService SearchServiceInterface) *SearchHandlers {
SearchHandlersInstance = &SearchHandlers{
searchService: searchService,
}
return SearchHandlersInstance
}
2025-12-03 19:29:37 +00:00
// Search performs a full-text search across tracks, users, and playlists
func (sh *SearchHandlers) Search(c *gin.Context) {
query := c.Query("q")
if query == "" {
2026-03-06 18:13:16 +00:00
RespondWithAppError(c, apperrors.NewValidationError("Search query is required"))
2025-12-03 19:29:37 +00:00
return
}
types := c.QueryArray("type")
results, err := sh.searchService.Search(query, types)
if err != nil {
2026-03-06 18:13:16 +00:00
RespondWithAppError(c, apperrors.NewInternalErrorWrap("Search failed", err))
2025-12-03 19:29:37 +00:00
return
}
RespondSuccess(c, http.StatusOK, results)
}
// Suggestions returns autocomplete suggestions for the search input
func (sh *SearchHandlers) Suggestions(c *gin.Context) {
query := c.Query("q")
if query == "" {
2026-03-06 18:13:16 +00:00
RespondWithAppError(c, apperrors.NewValidationError("Query parameter 'q' is required"))
return
}
limit := 5
if l := c.Query("limit"); l != "" {
if n, err := parseInt(l); err == nil && n > 0 && n <= 20 {
limit = n
}
}
results, err := sh.searchService.Suggestions(query, limit)
if err != nil {
2026-03-06 18:13:16 +00:00
RespondWithAppError(c, apperrors.NewInternalErrorWrap("Suggestions failed", err))
return
}
RespondSuccess(c, http.StatusOK, results)
}
func parseInt(s string) (int, error) {
return strconv.Atoi(s)
}