GoBlog/commentsAdmin.go

98 lines
2.2 KiB
Go
Raw Normal View History

2021-02-17 15:07:42 +00:00
package main
import (
"fmt"
"net/http"
"reflect"
"strconv"
2022-03-16 07:28:03 +00:00
"sync"
2021-02-17 15:07:42 +00:00
2021-03-03 17:19:55 +00:00
"github.com/go-chi/chi/v5"
2021-02-17 15:07:42 +00:00
"github.com/vcraescu/go-paginator"
)
type commentsPaginationAdapter struct {
2022-03-16 07:28:03 +00:00
config *commentsRequestConfig
nums int64
getNums sync.Once
db *database
2021-02-17 15:07:42 +00:00
}
func (p *commentsPaginationAdapter) Nums() (int64, error) {
2022-03-16 07:28:03 +00:00
p.getNums.Do(func() {
nums, _ := p.db.countComments(p.config)
2021-02-17 15:07:42 +00:00
p.nums = int64(nums)
2022-03-16 07:28:03 +00:00
})
2021-02-17 15:07:42 +00:00
return p.nums, nil
}
2022-03-16 07:28:03 +00:00
func (p *commentsPaginationAdapter) Slice(offset, length int, data any) error {
2021-02-17 15:07:42 +00:00
modifiedConfig := *p.config
modifiedConfig.offset = offset
modifiedConfig.limit = length
comments, err := p.db.getComments(&modifiedConfig)
2021-02-17 15:07:42 +00:00
reflect.ValueOf(data).Elem().Set(reflect.ValueOf(&comments).Elem())
return err
}
func (a *goBlog) commentsAdmin(w http.ResponseWriter, r *http.Request) {
commentsPath := r.Context().Value(pathKey).(string)
// Adapter
p := paginator.New(&commentsPaginationAdapter{config: &commentsRequestConfig{}, db: a.db}, 5)
2022-02-26 19:38:52 +00:00
p.SetPage(stringToInt(chi.URLParam(r, "page")))
var comments []*comment
err := p.Results(&comments)
if err != nil {
a.serveError(w, r, err.Error(), http.StatusInternalServerError)
return
}
// Navigation
var hasPrev, hasNext bool
var prevPage, nextPage int
var prevPath, nextPath string
hasPrev, _ = p.HasPrev()
if hasPrev {
prevPage, _ = p.PrevPage()
} else {
prevPage, _ = p.Page()
}
if prevPage < 2 {
prevPath = commentsPath
} else {
prevPath = fmt.Sprintf("%s/page/%d", commentsPath, prevPage)
}
hasNext, _ = p.HasNext()
if hasNext {
nextPage, _ = p.NextPage()
} else {
nextPage, _ = p.Page()
2021-02-17 15:07:42 +00:00
}
nextPath = fmt.Sprintf("%s/page/%d", commentsPath, nextPage)
// Render
a.render(w, r, a.renderCommentsAdmin, &renderData{
Data: &commentsRenderData{
comments: comments,
hasPrev: hasPrev,
hasNext: hasNext,
prev: prevPath,
next: nextPath,
},
})
2021-02-17 15:07:42 +00:00
}
func (a *goBlog) commentsAdminDelete(w http.ResponseWriter, r *http.Request) {
2021-02-17 15:07:42 +00:00
id, err := strconv.Atoi(r.FormValue("commentid"))
if err != nil {
a.serveError(w, r, err.Error(), http.StatusBadRequest)
2021-02-17 15:07:42 +00:00
return
}
err = a.db.deleteComment(id)
2021-02-17 15:07:42 +00:00
if err != nil {
a.serveError(w, r, err.Error(), http.StatusInternalServerError)
2021-02-17 15:07:42 +00:00
return
}
a.cache.purge()
2021-02-17 15:07:42 +00:00
http.Redirect(w, r, ".", http.StatusFound)
}