version 1
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
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
This commit is contained in:
@@ -0,0 +1,63 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"github.com/dusiburg/fancy-api/internal/model"
|
||||
"github.com/dusiburg/fancy-api/internal/provider/translation"
|
||||
"github.com/dusiburg/fancy-api/internal/service"
|
||||
)
|
||||
|
||||
type TranslationHandler struct {
|
||||
service *service.TranslationService
|
||||
}
|
||||
|
||||
func NewTranslationHandler(svc *service.TranslationService) *TranslationHandler {
|
||||
return &TranslationHandler{service: svc}
|
||||
}
|
||||
|
||||
type translateRequest struct {
|
||||
Text string `json:"text" binding:"required"`
|
||||
From string `json:"from"`
|
||||
To string `json:"to"`
|
||||
}
|
||||
|
||||
func (h *TranslationHandler) Translate(c *gin.Context) {
|
||||
var req translateRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
from, ok := model.ParseLanguage(req.From)
|
||||
if !ok {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "unsupported source language"})
|
||||
return
|
||||
}
|
||||
|
||||
to, ok := model.ParseLanguage(req.To)
|
||||
if !ok {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "unsupported target language"})
|
||||
return
|
||||
}
|
||||
|
||||
text := strings.TrimSpace(req.Text)
|
||||
result, err := h.service.Translate(c.Request.Context(), text, from, to)
|
||||
if err != nil {
|
||||
switch {
|
||||
case errors.Is(err, translation.ErrUnsupportedLanguage):
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "unsupported language"})
|
||||
case errors.Is(err, translation.ErrQuotaExceeded):
|
||||
c.JSON(http.StatusTooManyRequests, gin.H{"error": "translation quota exceeded"})
|
||||
default:
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "translation failed"})
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, result)
|
||||
}
|
||||
Reference in New Issue
Block a user