Files
scrap/api/article/handler.go
2025-10-04 23:14:41 +02:00

79 lines
1.7 KiB
Go

package article
import (
"net/http"
"scrap/api/httpio"
"scrap/internal/article"
"scrap/internal/db"
)
func ArticleDownloadHandler(w http.ResponseWriter, r *http.Request) {
dbInstance := db.GetInstance()
txRepo := db.NewTxRepository(dbInstance)
articleRepo := article.NewArticleRepository()
service := article.NewArticleService(txRepo, articleRepo)
if err := service.DownloadArticles(); err != nil {
switch err {
default:
httpio.RaiseOnlyStatusCode(w, http.StatusInternalServerError)
}
return
}
}
func ArticleQueryHandler(w http.ResponseWriter, r *http.Request) {
body, err := httpio.ParseURLQuery[ArticleQueryRequest](
r,
httpio.URLQueryKey[string]("title"),
)
if err != nil {
httpio.RaiseOnlyStatusCode(w, http.StatusInternalServerError)
return
}
if httpErr := body.Validate(); httpErr != nil {
httpErr.Raise(w)
return
}
dbInstance := db.GetInstance()
txRepo := db.NewTxRepository(dbInstance)
articleRepo := article.NewArticleRepository()
service := article.NewArticleService(txRepo, articleRepo)
articleQueryData := article.ArticleQueryDTO{
Title: body.Title,
}
articles, err := service.QueryArticles(articleQueryData)
if err != nil {
switch err {
case article.ErrArticleTitleInvalidLength:
ErrHttpArticleTitleInvalidLength.Raise(w)
default:
httpio.RaiseOnlyStatusCode(w, http.StatusInternalServerError)
}
return
}
articlesOut := make([]ArticleResponse, 0, len(articles))
for _, a := range articles {
ar := ArticleResponse{
Uuid: a.Uuid,
Title: a.Title,
Content: a.Content,
}
articlesOut = append(articlesOut, ar)
}
if err = ArticleQueryResponse(articlesOut).Return(w, http.StatusOK); err != nil {
httpio.RaiseOnlyStatusCode(w, http.StatusInternalServerError)
return
}
}