Files
bibliomane/internal/routes/bookpostimport.go

107 lines
3.0 KiB
Go

package routes
import (
"errors"
"git.artlef.fr/PersonalLibraryManager/internal/appcontext"
"git.artlef.fr/PersonalLibraryManager/internal/dto"
"git.artlef.fr/PersonalLibraryManager/internal/inventaire"
"git.artlef.fr/PersonalLibraryManager/internal/model"
"git.artlef.fr/PersonalLibraryManager/internal/myvalidator"
"git.artlef.fr/PersonalLibraryManager/internal/openlibrary"
"github.com/gin-gonic/gin"
"gorm.io/gorm"
)
func PostImportBookHandler(ac appcontext.AppContext) {
var request dto.BookPostImport
err := ac.C.ShouldBindJSON(&request)
if err != nil {
myvalidator.ReturnErrorsAsJsonResponse(&ac, err)
return
}
user, fetchUserErr := ac.GetAuthenticatedUser()
if fetchUserErr != nil {
myvalidator.ReturnErrorsAsJsonResponse(&ac, err)
return
}
inventaireEdition, err := inventaire.CallInventaireEdition(request.InventaireID, request.Lang)
if err != nil {
myvalidator.ReturnErrorsAsJsonResponse(&ac, err)
return
}
book, err := saveInventaireBookToDb(ac, inventaireEdition, &user)
if err != nil {
myvalidator.ReturnErrorsAsJsonResponse(&ac, err)
return
}
ac.C.JSON(200, gin.H{"id": book.ID})
}
func saveInventaireBookToDb(ac appcontext.AppContext, inventaireEdition inventaire.InventaireEditionDetailedSingleResult, user *model.User) (*model.Book, error) {
author, err := fetchOrCreateInventaireAuthor(ac, inventaireEdition.Author)
if err != nil {
return nil, err
}
book := model.Book{
Title: inventaireEdition.Title,
SmallDescription: inventaireEdition.Description,
InventaireID: inventaireEdition.Id,
Author: *author,
AddedBy: *user,
}
err = ac.Db.Save(&book).Error
return &book, err
}
func fetchOrCreateInventaireAuthor(ac appcontext.AppContext, inventaireAuthor *inventaire.InventaireAuthorResult) (*model.Author, error) {
var author model.Author
res := ac.Db.Where("inventaire_id = ?", inventaireAuthor.ID).First(&author)
err := res.Error
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
newAuthor := model.Author{
Name: inventaireAuthor.Name,
Description: inventaireAuthor.Description,
InventaireID: inventaireAuthor.ID,
}
return &newAuthor, nil
} else {
return &author, err
}
} else {
return &author, nil
}
}
func createAuthorFromOpenLibrary(ac appcontext.AppContext, openlibraryAuthorId string) (*model.Author, error) {
authorFromOL, err := openlibrary.CallOpenLibraryAuthor(openlibraryAuthorId)
if err != nil {
return nil, err
}
var author model.Author
res := ac.Db.Where("name = ?", authorFromOL.Name).First(&author)
err = res.Error
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
author = model.Author{
Name: authorFromOL.Name,
Description: authorFromOL.Description,
OpenLibraryId: openlibraryAuthorId,
}
err = ac.Db.Save(&author).Error
return &author, err
} else {
return nil, err
}
} else {
//if the author already exists, only fill the open library id
author.OpenLibraryId = openlibraryAuthorId
ac.Db.Save(&author)
}
return &author, err
}