feat: mark book as read
This commit is contained in:
63
internal/routes/bookpostread.go
Normal file
63
internal/routes/bookpostread.go
Normal file
@@ -0,0 +1,63 @@
|
||||
package routes
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
"git.artlef.fr/PersonalLibraryManager/internal/appcontext"
|
||||
"git.artlef.fr/PersonalLibraryManager/internal/model"
|
||||
"git.artlef.fr/PersonalLibraryManager/internal/myvalidator"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type bookPostMarkAsRead struct {
|
||||
BookID uint `json:"bookId" binding:"required"`
|
||||
}
|
||||
|
||||
func PostBookReadHandler(ac appcontext.AppContext) {
|
||||
var userbook bookPostMarkAsRead
|
||||
err := ac.C.ShouldBindJSON(&userbook)
|
||||
if err != nil {
|
||||
myvalidator.ReturnErrorsAsJsonResponse(&ac, err)
|
||||
return
|
||||
}
|
||||
err = myvalidator.ValidateId(ac.Db, userbook.BookID, &model.Book{})
|
||||
if err != nil {
|
||||
myvalidator.ReturnErrorsAsJsonResponse(&ac, err)
|
||||
return
|
||||
}
|
||||
user, fetchUserErr := ac.GetAuthenticatedUser()
|
||||
if fetchUserErr != nil {
|
||||
myvalidator.ReturnErrorsAsJsonResponse(&ac, err)
|
||||
return
|
||||
}
|
||||
|
||||
var userbookDb model.UserBook
|
||||
res := ac.Db.Where("user_id = ? AND book_id = ?", user.ID, userbook.BookID).First(&userbookDb)
|
||||
err = res.Error
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
userbookDb = userBookWsToDb(userbook, &user)
|
||||
err = ac.Db.Save(&userbookDb).Error
|
||||
if err != nil {
|
||||
myvalidator.ReturnErrorsAsJsonResponse(&ac, err)
|
||||
return
|
||||
}
|
||||
} else {
|
||||
myvalidator.ReturnErrorsAsJsonResponse(&ac, err)
|
||||
return
|
||||
}
|
||||
} else {
|
||||
userbookDb.Read = true
|
||||
ac.Db.Save(&userbookDb)
|
||||
}
|
||||
ac.C.String(http.StatusOK, "Success")
|
||||
}
|
||||
|
||||
func userBookWsToDb(ub bookPostMarkAsRead, user *model.User) model.UserBook {
|
||||
return model.UserBook{
|
||||
UserID: user.ID,
|
||||
BookID: ub.BookID,
|
||||
Read: true,
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user