Files
Ivan Rezchikov 628dd6384b
Build and Deploy / test-backend (push) Successful in 1m11s
Build and Deploy / lint-frontend (push) Successful in 21s
Build and Deploy / build-backend (push) Successful in 58s
Build and Deploy / deploy (push) Canceled after 0s
Build and Deploy / build-frontend (push) Canceled after 5m38s
version 1
2026-09-18 00:45:51 +03:00

58 lines
1.5 KiB
Go

package handler
import (
"errors"
"log"
"net/http"
"strings"
"github.com/dusiburg/fancy-api/internal/model"
"github.com/dusiburg/fancy-api/internal/provider/examples"
"github.com/dusiburg/fancy-api/internal/service"
"github.com/gin-gonic/gin"
)
type ExamplesHandler struct {
service *service.ExamplesService
}
func NewExamplesHandler(service *service.ExamplesService) *ExamplesHandler {
return &ExamplesHandler{service: service}
}
func (h *ExamplesHandler) GenerateExamples(c *gin.Context) {
word := strings.ToLower(strings.TrimSpace(c.Param("word")))
if word == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "word is required"})
return
}
lang, ok := model.ParseLanguage(c.Param("lang"))
if !ok {
c.JSON(http.StatusBadRequest, gin.H{"error": "unsupported language"})
return
}
userID, ok := userIDFromContext(c)
if !ok {
c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
return
}
result, err := h.service.GenerateExamples(c, userID, word, lang)
if err != nil {
log.Printf("generate examples %q [%s]: %v", word, lang, err)
switch {
case errors.Is(err, examples.ErrUnsupportedLanguage):
c.JSON(http.StatusBadRequest, gin.H{"error": "unsupported language"})
case errors.Is(err, examples.ErrQuotaExceeded):
c.JSON(http.StatusTooManyRequests, gin.H{"error": "limit exceeded"})
default:
c.JSON(http.StatusInternalServerError, gin.H{"error": "examples generation failed"})
}
return
}
c.JSON(http.StatusOK, result)
}