64 lines
1.4 KiB
Go
64 lines
1.4 KiB
Go
package adapter
|
|
|
|
import (
|
|
"errors"
|
|
|
|
"git.artlef.fr/bibliomane/internal/appcontext"
|
|
"git.artlef.fr/bibliomane/internal/dto"
|
|
"git.artlef.fr/bibliomane/internal/model"
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
func FillBookDbFromFields(ac appcontext.AppContext, fields *dto.BookFields, book *model.Book) error {
|
|
if fields.Title != nil {
|
|
book.Title = *fields.Title
|
|
}
|
|
if fields.ISBN != nil {
|
|
book.ISBN = *fields.ISBN
|
|
}
|
|
if fields.InventaireID != nil {
|
|
book.InventaireID = *fields.InventaireID
|
|
}
|
|
if fields.OpenLibraryId != nil {
|
|
book.OpenLibraryId = *fields.OpenLibraryId
|
|
}
|
|
if fields.ShortDescription != nil {
|
|
book.ShortDescription = *fields.ShortDescription
|
|
}
|
|
if fields.Summary != nil {
|
|
book.Summary = *fields.Summary
|
|
}
|
|
if fields.CoverID != nil {
|
|
book.CoverID = *fields.CoverID
|
|
}
|
|
|
|
if fields.Author != nil {
|
|
author, err := fetchOrCreateAuthor(ac, *fields.Author)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
book.AuthorID = author.ID
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func fetchOrCreateAuthor(ac appcontext.AppContext, name string) (*model.Author, error) {
|
|
var author model.Author
|
|
res := ac.Db.Where("name = ?", name).First(&author)
|
|
err := res.Error
|
|
if err != nil {
|
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
|
author = model.Author{Name: name}
|
|
err = ac.Db.Save(&author).Error
|
|
if err != nil {
|
|
return &author, err
|
|
}
|
|
return &author, nil
|
|
} else {
|
|
return &author, err
|
|
}
|
|
} else {
|
|
return &author, nil
|
|
}
|
|
}
|