package routes import ( "errors" "net/http" "strconv" "git.artlef.fr/bibliomane/internal/adapter" "git.artlef.fr/bibliomane/internal/appcontext" "git.artlef.fr/bibliomane/internal/dto" "git.artlef.fr/bibliomane/internal/i18nresource" "git.artlef.fr/bibliomane/internal/myvalidator" "git.artlef.fr/bibliomane/internal/query" "github.com/gin-gonic/gin" ) func GetCollectionHandler(ac appcontext.AppContext) { collectionId, err := strconv.ParseUint(ac.C.Param("id"), 10, 64) if err != nil { ac.C.JSON(http.StatusBadRequest, gin.H{"error": err}) return } 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 } collectionHeader, err := query.FetchCollectionHeader(ac.Db, uint(collectionId)) if collectionHeader.UserID != user.ID { err := myvalidator.HttpError{ StatusCode: http.StatusUnauthorized, Err: errors.New(i18nresource.GetTranslatedMessage(&ac, "Unauthorized")), } myvalidator.ReturnErrorsAsJsonResponse(&ac, err) return } collection := dto.CollectionGet{Name: collectionHeader.Name} if err != nil { myvalidator.ReturnErrorsAsJsonResponse(&ac, err) return } itemsQueryResult, err := query.FetchCollectionItems(ac.Db, user.ID, uint(collectionId), limit, offset) if err != nil { myvalidator.ReturnErrorsAsJsonResponse(&ac, err) return } items := adapter.CollectionItemsQueryToDto(itemsQueryResult) collection.Items = items count, err := query.FetchCollectionBooksCount(ac.Db, user.ID, uint(collectionId)) if err != nil { myvalidator.ReturnErrorsAsJsonResponse(&ac, err) return } collection.Count = count ac.C.JSON(http.StatusOK, collection) }