First implementation of fetching collections of book managed by user

This commit is contained in:
2026-04-02 16:23:22 +02:00
parent acdc3972bd
commit a280647575
18 changed files with 377 additions and 41 deletions

View File

@@ -184,6 +184,59 @@ func selectBookItem() string {
return "books.id, books.title, authors.name as author, books.short_description as description, books.inventaire_id, user_books.rating, user_books.read, DATE(user_books.start_read_date) as start_read_date, user_books.want_read, " + selectStaticFilesPath()
}
type CollectionsQueryResult struct {
ID uint
Name string
BookId uint
BookTitle string
CoverPath string
}
type collectionId struct {
ID uint
}
func FetchAllCollections(db *gorm.DB, userId uint, limit int, offset int) ([]CollectionsQueryResult, error) {
var collections []CollectionsQueryResult
var collectionIds []collectionId
res := fetchCollections(db, userId).Limit(limit).Offset(offset).Find(&collectionIds)
if res.Error != nil {
return collections, res.Error
}
for _, collectionId := range collectionIds {
queryResults, err := queryBooksForCollection(db, collectionId.ID)
if err != nil {
return collections, res.Error
}
collections = append(collections, queryResults...)
}
return collections, res.Error
}
func queryBooksForCollection(db *gorm.DB, collectionId uint) ([]CollectionsQueryResult, error) {
var collections []CollectionsQueryResult
query := db.Model(&model.Collection{})
query = query.Select("collections.id, collections.name, books.id as book_id, books.title as book_title, " + selectStaticFilesPath())
query = query.Joins("left join collection_books on (collection_books.collection_id = collections.id)")
query = query.Joins("left join books on (books.id = collection_books.book_id)")
query = joinStaticFiles(query)
query = query.Where("collections.id = ?", collectionId)
//only takes first 5 books
query = query.Limit(5)
res := query.Find(&collections)
return collections, res.Error
}
func FetchAllCollectionsCount(db *gorm.DB, userId uint) (int64, error) {
var count int64
res := fetchCollections(db, userId).Count(&count)
return count, res.Error
}
func fetchCollections(db *gorm.DB, userId uint) *gorm.DB {
return db.Model(&model.Collection{}).Where("collections.user_id = ?", userId)
}
func selectStaticFilesPath() string {
return "(CASE COALESCE(static_files.path, '') WHEN '' THEN '' ELSE concat('" + fileutils.GetWsLinkPrefix() + "', static_files.path) END) as CoverPath"
}