328 lines
8.5 KiB
Go
328 lines
8.5 KiB
Go
package article
|
|
|
|
import (
|
|
"RenewCMS/api/pkg/apperr"
|
|
"RenewCMS/api/pkg/claims"
|
|
validator "RenewCMS/api/pkg/validator"
|
|
domain "RenewCMS/internal/domain/article"
|
|
"RenewCMS/internal/infrastructure/useCases"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"log"
|
|
"net/http"
|
|
"strconv"
|
|
"time"
|
|
|
|
"github.com/go-chi/chi/v5"
|
|
)
|
|
|
|
type Handler struct {
|
|
CreateUseCase *useCases.CreateArticleUseCase
|
|
GetUseCase *useCases.GetArticleUseCase
|
|
ListUseCase *useCases.ListArticlesUseCase
|
|
DeleteUseCase *useCases.DeleteArticleUseCase
|
|
UpdateUseCase *useCases.UpdateArticleUseCase
|
|
GetUserUseCase *useCases.GetUserUseCase
|
|
}
|
|
|
|
type PostArticle struct {
|
|
Title string `json:"title" validate:"required,min=3,max=200"`
|
|
Body string `json:"body" validate:"required,max=10000"`
|
|
}
|
|
|
|
func NewHandler(create *useCases.CreateArticleUseCase, get *useCases.GetArticleUseCase, list *useCases.ListArticlesUseCase, delete *useCases.DeleteArticleUseCase, update *useCases.UpdateArticleUseCase, getUser *useCases.GetUserUseCase) *Handler {
|
|
return &Handler{
|
|
CreateUseCase: create,
|
|
GetUseCase: get,
|
|
ListUseCase: list,
|
|
DeleteUseCase: delete,
|
|
UpdateUseCase: update,
|
|
GetUserUseCase: getUser,
|
|
}
|
|
}
|
|
|
|
type articleResponse struct {
|
|
ID uint32 `json:"id"`
|
|
Title string `json:"title"`
|
|
Body json.RawMessage `json:"body"`
|
|
BodyFormat domain.BodyFormat `json:"body_format"`
|
|
IsOnline bool `json:"is_online"`
|
|
CreatedAt time.Time `json:"created_at"`
|
|
UpdatedAt time.Time `json:"updated_at"`
|
|
}
|
|
|
|
func toArticleResponse(article domain.Article, format domain.BodyFormat) (articleResponse, error) {
|
|
body := json.RawMessage(article.Body)
|
|
if format != domain.BodyFormatJSON {
|
|
encoded, err := json.Marshal(article.Body)
|
|
if err != nil {
|
|
return articleResponse{}, err
|
|
}
|
|
body = encoded
|
|
}
|
|
return articleResponse{
|
|
ID: article.ID,
|
|
Title: article.Title,
|
|
Body: body,
|
|
BodyFormat: format,
|
|
IsOnline: article.IsOnline,
|
|
CreatedAt: article.CreatedAt,
|
|
UpdatedAt: article.UpdatedAt,
|
|
}, nil
|
|
}
|
|
|
|
func encodeArticle(article domain.Article, format domain.BodyFormat) ([]byte, error) {
|
|
response, err := toArticleResponse(article, format)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return json.Marshal(response)
|
|
}
|
|
|
|
func parseBodyFormat(w http.ResponseWriter, r *http.Request) (domain.BodyFormat, bool) {
|
|
format, err := domain.ParseBodyFormat(r.URL.Query().Get("format"))
|
|
if err != nil {
|
|
http.Error(w, apperr.ArticleBodyFormatErrorMessage, http.StatusBadRequest)
|
|
return "", false
|
|
}
|
|
return format, true
|
|
}
|
|
|
|
func parseArticleId(r *http.Request) (uint32, error) {
|
|
id, err := strconv.ParseUint(chi.URLParam(r, "id"), 10, 32)
|
|
return uint32(id), err
|
|
}
|
|
|
|
func (h *Handler) GetArticle(w http.ResponseWriter, r *http.Request) {
|
|
id, err := parseArticleId(r)
|
|
if err != nil {
|
|
http.Error(w, apperr.IdUint32ErrorMessage, http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
format, ok := parseBodyFormat(w, r)
|
|
if !ok {
|
|
return
|
|
}
|
|
|
|
var article domain.Article
|
|
if h.callerIsVerified(r) {
|
|
article, err = h.GetUseCase.GetArticle(id, format)
|
|
} else {
|
|
article, err = h.GetUseCase.GetOnlineArticle(id, format)
|
|
}
|
|
if err != nil {
|
|
if errors.Is(err, domain.ErrArticleNotFound) {
|
|
http.Error(w, apperr.ArticleNotFoundErrorMessage, http.StatusNotFound)
|
|
return
|
|
}
|
|
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
|
|
articleJson, err := encodeArticle(article, format)
|
|
if err != nil {
|
|
http.Error(w, "Failed to encode response", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
|
|
if _, err := w.Write(articleJson); err != nil {
|
|
fmt.Printf("Failed to write response: %v", err)
|
|
}
|
|
}
|
|
|
|
func (h *Handler) PostArticle(w http.ResponseWriter, r *http.Request) {
|
|
format, ok := parseBodyFormat(w, r)
|
|
if !ok {
|
|
return
|
|
}
|
|
|
|
var localArticle PostArticle
|
|
if err := json.NewDecoder(r.Body).Decode(&localArticle); err != nil {
|
|
http.Error(w, apperr.BodyErrorMessage, http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
if err := validator.Validate.Struct(localArticle); err != nil {
|
|
http.Error(w, err.Error(), http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
createdArticle, err := h.CreateUseCase.CreateArticle(useCases.CreateArticleCommand{
|
|
Title: localArticle.Title,
|
|
Body: localArticle.Body,
|
|
Format: format,
|
|
})
|
|
if err != nil {
|
|
if errors.Is(err, domain.ErrInvalidTitle) {
|
|
http.Error(w, apperr.ArticleTitleErrorMessage, http.StatusBadRequest)
|
|
return
|
|
}
|
|
http.Error(w, "Failed to create article", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
|
|
writeArticleJsonResponse(w, http.StatusCreated, createdArticle, format)
|
|
}
|
|
|
|
func writeArticleErrorResponse(w http.ResponseWriter, err error) {
|
|
if errors.Is(err, domain.ErrArticleNotFound) {
|
|
http.Error(w, apperr.ArticleNotFoundErrorMessage, http.StatusNotFound)
|
|
return
|
|
}
|
|
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
|
}
|
|
|
|
func writeArticleJsonResponse(w http.ResponseWriter, status int, article domain.Article, format domain.BodyFormat) {
|
|
articleJson, err := encodeArticle(article, format)
|
|
if err != nil {
|
|
http.Error(w, "Failed to encode response", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
|
|
if status != http.StatusOK {
|
|
w.WriteHeader(status)
|
|
}
|
|
if _, err := w.Write(articleJson); err != nil {
|
|
log.Printf("Failed to write response: %v", err)
|
|
}
|
|
}
|
|
|
|
func (h *Handler) setIsOnline(w http.ResponseWriter, r *http.Request, isOnline bool) {
|
|
id, err := parseArticleId(r)
|
|
if err != nil {
|
|
http.Error(w, apperr.IdUint32ErrorMessage, http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
format, ok := parseBodyFormat(w, r)
|
|
if !ok {
|
|
return
|
|
}
|
|
|
|
updatedArticle, err := h.UpdateUseCase.UpdateIsOnline(id, isOnline, format)
|
|
if err != nil {
|
|
writeArticleErrorResponse(w, err)
|
|
return
|
|
}
|
|
|
|
writeArticleJsonResponse(w, http.StatusOK, updatedArticle, format)
|
|
}
|
|
|
|
type UpdateArticleBody struct {
|
|
Body string `json:"body" validate:"required,max=10000"`
|
|
}
|
|
|
|
func (h *Handler) UpdateArticleBody(w http.ResponseWriter, r *http.Request) {
|
|
id, err := parseArticleId(r)
|
|
if err != nil {
|
|
http.Error(w, apperr.IdUint32ErrorMessage, http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
format, ok := parseBodyFormat(w, r)
|
|
if !ok {
|
|
return
|
|
}
|
|
|
|
var localArticle UpdateArticleBody
|
|
if err := json.NewDecoder(r.Body).Decode(&localArticle); err != nil {
|
|
http.Error(w, apperr.BodyErrorMessage, http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
if err := validator.Validate.Struct(localArticle); err != nil {
|
|
http.Error(w, err.Error(), http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
updatedArticle, err := h.UpdateUseCase.UpdateBody(id, localArticle.Body, format)
|
|
if err != nil {
|
|
writeArticleErrorResponse(w, err)
|
|
return
|
|
}
|
|
|
|
writeArticleJsonResponse(w, http.StatusOK, updatedArticle, format)
|
|
}
|
|
|
|
func (h *Handler) PublishArticle(w http.ResponseWriter, r *http.Request) {
|
|
h.setIsOnline(w, r, true)
|
|
}
|
|
|
|
func (h *Handler) UnpublishArticle(w http.ResponseWriter, r *http.Request) {
|
|
h.setIsOnline(w, r, false)
|
|
}
|
|
|
|
func (h *Handler) callerIsVerified(r *http.Request) bool {
|
|
userId, ok := claims.UserId(r)
|
|
if !ok {
|
|
return false
|
|
}
|
|
|
|
currentUser, err := h.GetUserUseCase.GetUser(userId)
|
|
if err != nil {
|
|
return false
|
|
}
|
|
|
|
return currentUser.IsVerified
|
|
}
|
|
|
|
func (h *Handler) ListArticles(w http.ResponseWriter, r *http.Request) {
|
|
format, ok := parseBodyFormat(w, r)
|
|
if !ok {
|
|
return
|
|
}
|
|
|
|
var articles []domain.Article
|
|
var err error
|
|
if h.callerIsVerified(r) {
|
|
articles, err = h.ListUseCase.ListAllArticles(format)
|
|
} else {
|
|
articles, err = h.ListUseCase.ListOnlineArticles(format)
|
|
}
|
|
if err != nil {
|
|
http.Error(w, "Failed to retrieve articles", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
|
|
responses := make([]articleResponse, 0, len(articles))
|
|
for _, article := range articles {
|
|
response, err := toArticleResponse(article, format)
|
|
if err != nil {
|
|
http.Error(w, "Failed to encode response", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
responses = append(responses, response)
|
|
}
|
|
|
|
articlesJson, err := json.Marshal(responses)
|
|
if err != nil {
|
|
http.Error(w, "Failed to encode response", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
|
|
if _, err := w.Write(articlesJson); err != nil {
|
|
log.Printf("Failed to write response: %v", err)
|
|
}
|
|
}
|
|
|
|
func (h *Handler) DeleteArticle(w http.ResponseWriter, r *http.Request) {
|
|
id, err := parseArticleId(r)
|
|
if err != nil {
|
|
http.Error(w, apperr.IdUint32ErrorMessage, http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
if err := h.DeleteUseCase.DeleteArticle(id); err != nil {
|
|
if errors.Is(err, domain.ErrArticleNotFound) {
|
|
http.Error(w, apperr.ArticleNotFoundErrorMessage, http.StatusNotFound)
|
|
return
|
|
}
|
|
http.Error(w, "Failed to delete article", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
|
|
w.WriteHeader(http.StatusNoContent)
|
|
}
|