Add route to get a particular book
This commit is contained in:
47
internal/routes/bookget.go
Normal file
47
internal/routes/bookget.go
Normal file
@@ -0,0 +1,47 @@
|
||||
package routes
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"git.artlef.fr/PersonalLibraryManager/internal/appcontext"
|
||||
"git.artlef.fr/PersonalLibraryManager/internal/model"
|
||||
"git.artlef.fr/PersonalLibraryManager/internal/myvalidator"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
type bookGet struct {
|
||||
Title string `json:"title" binding:"required,max=300"`
|
||||
Author string `json:"author" binding:"max=100"`
|
||||
Rating int `json:"rating"`
|
||||
Read bool `json:"read"`
|
||||
}
|
||||
|
||||
func GetBookHandler(ac appcontext.AppContext) {
|
||||
bookId, err := strconv.ParseUint(ac.C.Param("id"), 10, 64)
|
||||
if err != nil {
|
||||
ac.C.JSON(http.StatusBadRequest, gin.H{"error": err})
|
||||
return
|
||||
}
|
||||
user, fetchUserErr := ac.GetAuthenticatedUser()
|
||||
if fetchUserErr != nil {
|
||||
myvalidator.ReturnErrorsAsJsonResponse(&ac, fetchUserErr)
|
||||
return
|
||||
}
|
||||
err = myvalidator.ValidateId(ac.Db, uint(bookId), &model.Book{})
|
||||
if err != nil {
|
||||
myvalidator.ReturnErrorsAsJsonResponse(&ac, err)
|
||||
return
|
||||
}
|
||||
var book bookGet
|
||||
query := ac.Db.Model(&model.Book{})
|
||||
query = query.Select("books.title, books.author, user_books.rating, user_books.read")
|
||||
query = query.Joins("left join user_books on (user_books.book_id = books.id and user_books.user_id = ?)", user.ID)
|
||||
query = query.Where("books.id = ?", bookId)
|
||||
res := query.First(&book)
|
||||
if res.Error != nil {
|
||||
myvalidator.ReturnErrorsAsJsonResponse(&ac, err)
|
||||
return
|
||||
}
|
||||
ac.C.JSON(http.StatusOK, book)
|
||||
}
|
||||
Reference in New Issue
Block a user