tavern/web/handler_notifications.go

46 lines
1.0 KiB
Go

package web
import (
"net/http"
"strconv"
"time"
"github.com/gin-contrib/sessions"
"github.com/gin-gonic/gin"
"go.uber.org/zap"
"github.com/ngerakines/tavern/errors"
)
func (h handler) notifications(c *gin.Context) {
latest, err := strconv.Atoi(c.Query("latest"))
if err != nil {
h.internalServerErrorJSON(c, err)
return
}
session := sessions.Default(c)
ctx := c.Request.Context()
user, err := h.storage.GetUserBySession(ctx, session)
if err != nil {
if errors.Is(err, errors.UserSessionNotFoundError{}) {
h.unauthorizedJSON(c, err)
return
}
h.internalServerErrorJSON(c, err)
return
}
when := time.Unix(int64(latest), 0).Add(time.Second)
h.logger.Debug("looking up notifications", zap.String("user", user.Name), zap.Time("when", when))
count, err := h.storage.RowCount(c.Request.Context(), `SELECT COUNT(*) FROM user_feed WHERE user_id = $1 AND created_at > $2`, user.ID, when)
if err != nil {
h.internalServerErrorJSON(c, err)
return
}
c.JSON(http.StatusOK, gin.H{"count": count})
}