Added: downloading and returning wikipedia articles
This commit is contained in:
78
api/article/handler.go
Normal file
78
api/article/handler.go
Normal file
@@ -0,0 +1,78 @@
|
||||
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
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user