Files
bibliomane/internal/adapter/adapter.go

110 lines
2.9 KiB
Go

package adapter
import (
"errors"
"git.artlef.fr/bibliomane/internal/appcontext"
"git.artlef.fr/bibliomane/internal/dto"
"git.artlef.fr/bibliomane/internal/model"
"git.artlef.fr/bibliomane/internal/query"
"gorm.io/gorm"
)
func CollectionQueryToCollectionDto(collectionsQueryResult []query.CollectionsQueryResult) dto.CollectionGet {
var collection dto.CollectionGet
for _, collectionsDb := range collectionsQueryResult {
collection.Name = collectionsDb.Name
collection.Books = append(collection.Books, collectionDbToBookItem(&collectionsDb))
collection.UserID = collectionsDb.UserID
}
return collection
}
func CollectionQueryToCollectionItemDto(collectionsQueryResult []query.CollectionsQueryResult) []dto.CollectionItemGet {
var collections []dto.CollectionItemGet
for _, collectionDb := range collectionsQueryResult {
i := findIdInCollection(collections, collectionDb.ID)
if i == -1 {
collections = append(collections, dto.CollectionItemGet{
ID: collectionDb.ID,
Name: collectionDb.Name,
})
//current collection is the last element
i = len(collections) - 1
}
collections[i].Books = append(collections[i].Books, collectionDbToBookItem(&collectionDb))
}
return collections
}
func collectionDbToBookItem(collectionDb *query.CollectionsQueryResult) dto.CollectionBookItemGet {
return dto.CollectionBookItemGet{
ID: collectionDb.BookId,
Title: collectionDb.BookTitle,
CoverPath: collectionDb.CoverPath,
}
}
// returns the position in collections, -1 if not found
func findIdInCollection(collections []dto.CollectionItemGet, collectionId uint) int {
for i, collection := range collections {
if collection.ID == collectionId {
return i
}
}
return -1
}
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
}
}