go-dette/middleware.go

55 lines
1.2 KiB
Go

package main
import (
"context"
"log"
"time"
"git.nefrace.ru/nefrace/nechotron"
"git.nefrace.ru/nefrace/tongo"
)
func UserLogger(next nechotron.UpdateHandler) nechotron.UpdateHandler {
return func(u *nechotron.Update) error {
log.Println(u.From().FirstName)
err := next(u)
return err
}
}
func UserDBUpdater(db *tongo.Database) nechotron.Middleware {
return func(next nechotron.UpdateHandler) nechotron.UpdateHandler {
return func(u *nechotron.Update) error {
store := tongo.NewStore[User](db)
from := u.From()
user, err := store.GetOne(u.Ctx, tongo.E("id", from.ID))
if err != nil {
user = &User{
Item: tongo.NewID(),
ID: from.ID,
}
}
user.FirstName = from.FirstName
user.LastName = from.LastName
user.Username = from.Username
user.LastMessage = time.Now()
err = store.ReplaceItem(u.Ctx, *user, true)
if err != nil {
log.Println("Cant replace user: ", err)
}
u.Ctx = context.WithValue(u.Ctx, "dbuser", user)
return next(u)
}
}
}
func ErrorLogger(next nechotron.UpdateHandler) nechotron.UpdateHandler {
return func(u *nechotron.Update) error {
err := next(u)
if err != nil {
u.LogError("", err, true)
}
return err
}
}