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

@@ -6,9 +6,41 @@ import (
"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 CollectionQueryToDto(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, dto.CollectionBookItemGet{
ID: collectionDb.BookId,
Title: collectionDb.BookTitle,
CoverPath: collectionDb.CoverPath,
})
}
return collections
}
// 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

View File

@@ -1,11 +1,7 @@
package apitest
import (
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"net/url"
"testing"
"git.artlef.fr/bibliomane/internal/dto"
@@ -14,45 +10,12 @@ import (
)
func TestFetchAllBooks(t *testing.T) {
result := testFetchBooks(t, "15", "0")
status, result := testFetchBooks(t, "15", "0")
assert.Equal(t, http.StatusOK, status)
assert.Equal(t, int64(31), result.Count)
assert.Equal(t, 15, len(result.Books))
}
func testFetchBooks(t *testing.T, limit string, offset string) dto.BookItemsGet {
router := testutils.TestSetup()
u, err := url.Parse("/ws/books")
if err != nil {
t.Error(err)
}
if limit != "" {
q := u.Query()
q.Set("limit", limit)
u.RawQuery = q.Encode()
}
if offset != "" {
q := u.Query()
q.Set("offset", offset)
u.RawQuery = q.Encode()
}
q := u.Query()
q.Set("lang", "fr")
u.RawQuery = q.Encode()
token := testutils.ConnectDemoUser(router)
req, _ := http.NewRequest("GET", u.String(), nil)
req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", token))
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
var result dto.BookItemsGet
s := w.Body.String()
err = json.Unmarshal([]byte(s), &result)
if err != nil {
t.Error(err)
}
assert.Equal(t, 200, w.Code)
return result
func testFetchBooks(t *testing.T, limit string, offset string) (int, dto.BookItemsGet) {
return testutils.TestFetchModel[dto.BookItemsGet](t, "/ws/books", limit, offset)
}

View File

@@ -0,0 +1,21 @@
package apitest
import (
"net/http"
"testing"
"git.artlef.fr/bibliomane/internal/dto"
"git.artlef.fr/bibliomane/internal/testutils"
"github.com/stretchr/testify/assert"
)
func TestFetchAllCollections_OK(t *testing.T) {
status, res := testFetchCollections(t, "10", "0")
assert.Equal(t, http.StatusOK, status)
assert.Equal(t, int64(3), res.Count)
assert.Equal(t, 3, len(res.Collections))
}
func testFetchCollections(t *testing.T, limit string, offset string) (int, dto.CollectionItemsGet) {
return testutils.TestFetchModel[dto.CollectionItemsGet](t, "/ws/collections", limit, offset)
}

View File

@@ -22,6 +22,7 @@ func Initdb(databasePath string, demoDataPath string) *gorm.DB {
db.AutoMigrate(&model.User{})
db.AutoMigrate(&model.UserBook{})
db.AutoMigrate(&model.StaticFile{})
db.AutoMigrate(&model.Collection{})
var book model.Book
queryResult := db.Limit(1).Find(&book)
if queryResult.RowsAffected == 0 && demoDataPath != "" {

View File

@@ -43,3 +43,20 @@ type BookItemGet struct {
WantRead bool `json:"wantread"`
CoverPath string `json:"coverPath"`
}
type CollectionItemsGet struct {
Count int64 `json:"count"`
Collections []CollectionItemGet `json:"collections"`
}
type CollectionItemGet struct {
ID uint `json:"id"`
Name string `json:"name"`
Books []CollectionBookItemGet `json:"books"`
}
type CollectionBookItemGet struct {
ID uint `json:"id"`
Title string `json:"title"`
CoverPath string `json:"coverPath"`
}

View File

@@ -0,0 +1,11 @@
package model
import "gorm.io/gorm"
type Collection struct {
gorm.Model
Name string
User User
UserID uint
Books []Book `gorm:"many2many:collection_books;"`
}

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"
}

View File

@@ -0,0 +1,41 @@
package routes
import (
"net/http"
"git.artlef.fr/bibliomane/internal/adapter"
"git.artlef.fr/bibliomane/internal/appcontext"
"git.artlef.fr/bibliomane/internal/dto"
"git.artlef.fr/bibliomane/internal/myvalidator"
"git.artlef.fr/bibliomane/internal/query"
)
func GetCollectionsHandler(ac appcontext.AppContext) {
user, err := ac.GetAuthenticatedUser()
if err != nil {
myvalidator.ReturnErrorsAsJsonResponse(&ac, err)
return
}
limit, err := ac.GetQueryLimit()
if err != nil {
myvalidator.ReturnErrorsAsJsonResponse(&ac, err)
return
}
offset, err := ac.GetQueryOffset()
if err != nil {
myvalidator.ReturnErrorsAsJsonResponse(&ac, err)
return
}
collectionsDb, err := query.FetchAllCollections(ac.Db, user.ID, limit, offset)
if err != nil {
myvalidator.ReturnErrorsAsJsonResponse(&ac, err)
return
}
collections := adapter.CollectionQueryToDto(collectionsDb)
count, err := query.FetchAllCollectionsCount(ac.Db, user.ID)
if err != nil {
myvalidator.ReturnErrorsAsJsonResponse(&ac, err)
return
}
ac.C.JSON(http.StatusOK, dto.CollectionItemsGet{Count: count, Collections: collections})
}

View File

@@ -78,6 +78,9 @@ func Setup(config *config.Config) *gin.Engine {
ws.GET("/author/:id/books", func(c *gin.Context) {
routes.GetAuthorBooksHandler(appcontext.AppContext{C: c, Db: db, I18n: bundle, Config: config})
})
ws.GET("/collections", func(c *gin.Context) {
routes.GetCollectionsHandler(appcontext.AppContext{C: c, Db: db, I18n: bundle, Config: config})
})
ws.POST("/auth/signup", func(c *gin.Context) {
routes.PostSignupHandler(appcontext.AppContext{C: c, Db: db, I18n: bundle, Config: config})
})

View File

@@ -6,6 +6,8 @@ import (
"log"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
@@ -65,3 +67,40 @@ func TestBookPutCallWithDemoPayload(t *testing.T, payload string, bookId string,
t.Errorf("%s", w.Body.String())
}
}
func TestFetchModel[T any](t *testing.T, urlpath string, limit string, offset string) (int, T) {
router := TestSetup()
u, err := url.Parse(urlpath)
if err != nil {
t.Error(err)
}
if limit != "" {
q := u.Query()
q.Set("limit", limit)
u.RawQuery = q.Encode()
}
if offset != "" {
q := u.Query()
q.Set("offset", offset)
u.RawQuery = q.Encode()
}
q := u.Query()
q.Set("lang", "fr")
u.RawQuery = q.Encode()
token := ConnectDemoUser(router)
req, _ := http.NewRequest("GET", u.String(), nil)
req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", token))
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
var result T
s := w.Body.String()
err = json.Unmarshal([]byte(s), &result)
if err != nil {
t.Error(err)
}
return w.Code, result
}