Add a view to see all books in a collection
This commit is contained in:
@@ -129,7 +129,7 @@ INSERT INTO user_books(created_at, user_id, book_id, start_read_date, rating) VA
|
|||||||
-- collections
|
-- collections
|
||||||
INSERT INTO collections(name, user_id) VALUES ('Littérature française',(SELECT id FROM users WHERE name = 'demo'));
|
INSERT INTO collections(name, user_id) VALUES ('Littérature française',(SELECT id FROM users WHERE name = 'demo'));
|
||||||
INSERT INTO collections(name, user_id) VALUES ('Nouvelles',(SELECT id FROM users WHERE name = 'demo'));
|
INSERT INTO collections(name, user_id) VALUES ('Nouvelles',(SELECT id FROM users WHERE name = 'demo'));
|
||||||
INSERT INTO collections(name, user_id) VALUES ('Non fiction',(SELECT id FROM users WHERE name = 'demo'));
|
INSERT INTO collections(name, user_id) VALUES ('Non fiction',(SELECT id FROM users WHERE name = 'demo2'));
|
||||||
|
|
||||||
INSERT INTO collection_books(collection_id, book_id) VALUES ((SELECT id FROM collections WHERE name = 'Littérature française'), (SELECT id FROM books WHERE title = 'Nord'));
|
INSERT INTO collection_books(collection_id, book_id) VALUES ((SELECT id FROM collections WHERE name = 'Littérature française'), (SELECT id FROM books WHERE title = 'Nord'));
|
||||||
INSERT INTO collection_books(collection_id, book_id) VALUES ((SELECT id FROM collections WHERE name = 'Littérature française'), (SELECT id FROM books WHERE title = 'Gargantua'));
|
INSERT INTO collection_books(collection_id, book_id) VALUES ((SELECT id FROM collections WHERE name = 'Littérature française'), (SELECT id FROM books WHERE title = 'Gargantua'));
|
||||||
|
|||||||
51
front/src/CollectionForm.vue
Normal file
51
front/src/CollectionForm.vue
Normal file
@@ -0,0 +1,51 @@
|
|||||||
|
<script setup>
|
||||||
|
import { computed, ref } from 'vue'
|
||||||
|
import { getCollection } from './api.js'
|
||||||
|
import CollectionFormBookItem from './CollectionFormBookItem.vue'
|
||||||
|
import Pagination from './Pagination.vue'
|
||||||
|
|
||||||
|
const props = defineProps({
|
||||||
|
id: String,
|
||||||
|
})
|
||||||
|
|
||||||
|
const limit = 5
|
||||||
|
const pageNumber = ref(1)
|
||||||
|
|
||||||
|
const offset = computed(() => (pageNumber.value - 1) * limit)
|
||||||
|
|
||||||
|
const data = ref(null)
|
||||||
|
const error = ref(null)
|
||||||
|
|
||||||
|
let totalElementsNumber = computed(() =>
|
||||||
|
typeof data != 'undefined' && data.value != null ? data.value['count'] : 0,
|
||||||
|
)
|
||||||
|
|
||||||
|
let pageTotal = computed(() => Math.ceil(totalElementsNumber.value / limit))
|
||||||
|
|
||||||
|
getCollection(data, error, props.id, limit, offset.value)
|
||||||
|
|
||||||
|
function pageChange(newPageNumber) {
|
||||||
|
pageNumber.value = newPageNumber
|
||||||
|
data.value = null
|
||||||
|
getCollection(data, error, props.id, limit, offset.value)
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div v-if="error">{{ $t('bookform.error', { error: error.message }) }}</div>
|
||||||
|
<div v-if="data">
|
||||||
|
<h2 class="title">{{ data.name }}</h2>
|
||||||
|
<div>
|
||||||
|
<CollectionFormBookItem v-for="book in data.books" :key="book.id" v-bind="book" />
|
||||||
|
</div>
|
||||||
|
<Pagination
|
||||||
|
class="mt-5"
|
||||||
|
:pageNumber="pageNumber"
|
||||||
|
:pageTotal="pageTotal"
|
||||||
|
maxItemDisplayed="11"
|
||||||
|
@pageChange="pageChange"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<style></style>
|
||||||
37
front/src/CollectionFormBookItem.vue
Normal file
37
front/src/CollectionFormBookItem.vue
Normal file
@@ -0,0 +1,37 @@
|
|||||||
|
<script setup>
|
||||||
|
import { getImagePathOrDefault } from './api.js'
|
||||||
|
import { computed } from 'vue'
|
||||||
|
|
||||||
|
const props = defineProps({
|
||||||
|
title: String,
|
||||||
|
coverPath: String,
|
||||||
|
})
|
||||||
|
const imagePathOrDefault = computed(() => getImagePathOrDefault(props.coverPath))
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div class="bookcontainer has-background-dark p-2 m-2">
|
||||||
|
<img class="mr-2" v-bind:src="imagePathOrDefault" v-bind:alt="title" />
|
||||||
|
<h3 class="centered subtitle">{{ title }}</h3>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<style>
|
||||||
|
img {
|
||||||
|
max-height: 200px;
|
||||||
|
max-width: 200px;
|
||||||
|
height: auto;
|
||||||
|
width: auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
.bookcontainer {
|
||||||
|
display: flex;
|
||||||
|
transition: ease-in-out 0.04s;
|
||||||
|
border-radius: 20px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.bookcontainer:hover {
|
||||||
|
transform: scale(1.01);
|
||||||
|
transition: ease-in-out 0.02s;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -1,26 +1,36 @@
|
|||||||
<script setup>
|
<script setup>
|
||||||
import { getImagePathOrDefault } from './api.js'
|
import { getImagePathOrDefault } from './api.js'
|
||||||
|
import { useRouter } from 'vue-router'
|
||||||
|
|
||||||
const props = defineProps({
|
const props = defineProps({
|
||||||
id: Number,
|
id: Number,
|
||||||
name: String,
|
name: String,
|
||||||
books: Array,
|
books: Array,
|
||||||
})
|
})
|
||||||
|
|
||||||
|
const router = useRouter()
|
||||||
|
|
||||||
|
function goToCollection() {
|
||||||
|
const collectionId = props.id
|
||||||
|
router.push(`/collection/${props.id}`)
|
||||||
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
<div class="collectioncontainer has-background-dark p-2">
|
<div class="collectioncontainer has-background-dark p-2" @click="goToCollection">
|
||||||
<div class="collectionheader">
|
<div class="collectionheader">
|
||||||
<h2 class="subtitle">
|
<h2 class="subtitle">
|
||||||
{{ props.name }}
|
{{ props.name }}
|
||||||
</h2>
|
</h2>
|
||||||
</div>
|
</div>
|
||||||
<div class="collectionpreviewbooks">
|
<div class="collectionpreviewbooks" v-if="props.books && props.books.length > 0">
|
||||||
<div class="bookpreview mx-1" v-for="book in props.books" :key="book.id">
|
<div class="bookpreview mx-1" v-for="book in props.books" :key="book.id">
|
||||||
<img v-bind:src="getImagePathOrDefault(book.coverPath)" v-bind:alt="book.title" />
|
<img v-bind:src="getImagePathOrDefault(book.coverPath)" v-bind:alt="book.title" />
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<style scoped>
|
<style scoped>
|
||||||
img {
|
img {
|
||||||
max-height: 100px;
|
max-height: 100px;
|
||||||
|
|||||||
@@ -60,6 +60,11 @@ export function getCollections(data, error, limit, offset) {
|
|||||||
return useFetch(data, error, '/ws/collections' + '?' + queryParams.toString())
|
return useFetch(data, error, '/ws/collections' + '?' + queryParams.toString())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function getCollection(data, error, id, limit, offset) {
|
||||||
|
const queryParams = new URLSearchParams({ limit: limit, offset: offset })
|
||||||
|
return useFetch(data, error, '/ws/collection/' + id + '?' + queryParams.toString())
|
||||||
|
}
|
||||||
|
|
||||||
export function getMyBooks(data, error, arg, limit, offset) {
|
export function getMyBooks(data, error, arg, limit, offset) {
|
||||||
const queryParams = new URLSearchParams({ limit: limit, offset: offset })
|
const queryParams = new URLSearchParams({ limit: limit, offset: offset })
|
||||||
return useFetch(data, error, '/ws/mybooks/' + arg + '?' + queryParams.toString())
|
return useFetch(data, error, '/ws/mybooks/' + arg + '?' + queryParams.toString())
|
||||||
|
|||||||
@@ -93,6 +93,9 @@
|
|||||||
"collections": {
|
"collections": {
|
||||||
"error": "Error when loading collections: {error}",
|
"error": "Error when loading collections: {error}",
|
||||||
"add": "Add a collection",
|
"add": "Add a collection",
|
||||||
"name": "Nom"
|
"name": "Name"
|
||||||
|
},
|
||||||
|
"collection": {
|
||||||
|
"error": "Error when loading collection: {error}"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -94,5 +94,8 @@
|
|||||||
"error": "Erreur pendant le chargement des listes: {error}",
|
"error": "Erreur pendant le chargement des listes: {error}",
|
||||||
"add": "Ajouter une liste",
|
"add": "Ajouter une liste",
|
||||||
"name": "Nom"
|
"name": "Nom"
|
||||||
|
},
|
||||||
|
"collection": {
|
||||||
|
"error": "Erreur pendant le chargement de la liste : {error}"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import { createRouter, createWebHistory } from 'vue-router'
|
|||||||
|
|
||||||
import BooksBrowser from './BooksBrowser.vue'
|
import BooksBrowser from './BooksBrowser.vue'
|
||||||
import CollectionsBrowser from './CollectionsBrowser.vue'
|
import CollectionsBrowser from './CollectionsBrowser.vue'
|
||||||
|
import CollectionForm from './CollectionForm.vue'
|
||||||
import BookFormEdit from './BookFormEdit.vue'
|
import BookFormEdit from './BookFormEdit.vue'
|
||||||
import AuthorForm from './AuthorForm.vue'
|
import AuthorForm from './AuthorForm.vue'
|
||||||
import BookFormView from './BookFormView.vue'
|
import BookFormView from './BookFormView.vue'
|
||||||
@@ -22,6 +23,7 @@ const routes = [
|
|||||||
{ path: '/book/:id', component: BookFormView, props: true },
|
{ path: '/book/:id', component: BookFormView, props: true },
|
||||||
{ path: '/book/:id/edit', component: BookFormEdit, props: true },
|
{ path: '/book/:id/edit', component: BookFormEdit, props: true },
|
||||||
{ path: '/collections', component: CollectionsBrowser },
|
{ path: '/collections', component: CollectionsBrowser },
|
||||||
|
{ path: '/collection/:id', component: CollectionForm, props: true },
|
||||||
{ path: '/author/:id', component: AuthorForm, props: true },
|
{ path: '/author/:id', component: AuthorForm, props: true },
|
||||||
{ path: '/search/:searchterm', component: SearchBook, props: true },
|
{ path: '/search/:searchterm', component: SearchBook, props: true },
|
||||||
{ path: '/import/inventaire/:inventaireid', component: ImportInventaire, props: true },
|
{ path: '/import/inventaire/:inventaireid', component: ImportInventaire, props: true },
|
||||||
|
|||||||
@@ -10,7 +10,17 @@ import (
|
|||||||
"gorm.io/gorm"
|
"gorm.io/gorm"
|
||||||
)
|
)
|
||||||
|
|
||||||
func CollectionQueryToDto(collectionsQueryResult []query.CollectionsQueryResult) []dto.CollectionItemGet {
|
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
|
var collections []dto.CollectionItemGet
|
||||||
for _, collectionDb := range collectionsQueryResult {
|
for _, collectionDb := range collectionsQueryResult {
|
||||||
i := findIdInCollection(collections, collectionDb.ID)
|
i := findIdInCollection(collections, collectionDb.ID)
|
||||||
@@ -22,13 +32,17 @@ func CollectionQueryToDto(collectionsQueryResult []query.CollectionsQueryResult)
|
|||||||
//current collection is the last element
|
//current collection is the last element
|
||||||
i = len(collections) - 1
|
i = len(collections) - 1
|
||||||
}
|
}
|
||||||
collections[i].Books = append(collections[i].Books, dto.CollectionBookItemGet{
|
collections[i].Books = append(collections[i].Books, collectionDbToBookItem(&collectionDb))
|
||||||
|
}
|
||||||
|
return collections
|
||||||
|
}
|
||||||
|
|
||||||
|
func collectionDbToBookItem(collectionDb *query.CollectionsQueryResult) dto.CollectionBookItemGet {
|
||||||
|
return dto.CollectionBookItemGet{
|
||||||
ID: collectionDb.BookId,
|
ID: collectionDb.BookId,
|
||||||
Title: collectionDb.BookTitle,
|
Title: collectionDb.BookTitle,
|
||||||
CoverPath: collectionDb.CoverPath,
|
CoverPath: collectionDb.CoverPath,
|
||||||
})
|
|
||||||
}
|
}
|
||||||
return collections
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// returns the position in collections, -1 if not found
|
// returns the position in collections, -1 if not found
|
||||||
|
|||||||
@@ -12,8 +12,8 @@ import (
|
|||||||
func TestFetchAllCollections_OK(t *testing.T) {
|
func TestFetchAllCollections_OK(t *testing.T) {
|
||||||
status, res := testFetchCollections(t, "10", "0")
|
status, res := testFetchCollections(t, "10", "0")
|
||||||
assert.Equal(t, http.StatusOK, status)
|
assert.Equal(t, http.StatusOK, status)
|
||||||
assert.Equal(t, int64(3), res.Count)
|
assert.Equal(t, int64(2), res.Count)
|
||||||
assert.Equal(t, 3, len(res.Collections))
|
assert.Equal(t, 2, len(res.Collections))
|
||||||
}
|
}
|
||||||
|
|
||||||
func testFetchCollections(t *testing.T, limit string, offset string) (int, dto.CollectionItemsGet) {
|
func testFetchCollections(t *testing.T, limit string, offset string) (int, dto.CollectionItemsGet) {
|
||||||
|
|||||||
@@ -1,10 +1,7 @@
|
|||||||
package apitest
|
package apitest
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"encoding/json"
|
|
||||||
"fmt"
|
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/http/httptest"
|
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"git.artlef.fr/bibliomane/internal/dto"
|
"git.artlef.fr/bibliomane/internal/dto"
|
||||||
@@ -61,20 +58,8 @@ func TestGetBook_IdNotInt(t *testing.T) {
|
|||||||
testGetBook(t, "wrong", http.StatusBadRequest)
|
testGetBook(t, "wrong", http.StatusBadRequest)
|
||||||
}
|
}
|
||||||
|
|
||||||
func testGetBook(t *testing.T, id string, status int) dto.FullBookGet {
|
func testGetBook(t *testing.T, id string, expectedStatus int) dto.FullBookGet {
|
||||||
router := testutils.TestSetup()
|
status, book := testutils.TestFetchOneModel[dto.FullBookGet](t, "/ws/book", id)
|
||||||
|
assert.Equal(t, expectedStatus, status)
|
||||||
token := testutils.ConnectDemoUser(router)
|
|
||||||
req, _ := http.NewRequest("GET", "/ws/book/"+id, nil)
|
|
||||||
req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", token))
|
|
||||||
w := httptest.NewRecorder()
|
|
||||||
router.ServeHTTP(w, req)
|
|
||||||
|
|
||||||
var book dto.FullBookGet
|
|
||||||
err := json.Unmarshal(w.Body.Bytes(), &book)
|
|
||||||
if err != nil {
|
|
||||||
t.Error(err)
|
|
||||||
}
|
|
||||||
assert.Equal(t, status, w.Code)
|
|
||||||
return book
|
return book
|
||||||
}
|
}
|
||||||
|
|||||||
34
internal/apitest/get_collection_test.go
Normal file
34
internal/apitest/get_collection_test.go
Normal file
@@ -0,0 +1,34 @@
|
|||||||
|
package apitest
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"git.artlef.fr/bibliomane/internal/dto"
|
||||||
|
"git.artlef.fr/bibliomane/internal/testutils"
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestGetCollection_Ok(t *testing.T) {
|
||||||
|
status, collection := testGetCollection(t, "1", "10", "0")
|
||||||
|
assert.Equal(t, http.StatusOK, status)
|
||||||
|
assert.Equal(t, "Littérature française", collection.Name)
|
||||||
|
assert.Equal(t, 6, len(collection.Books))
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestGetCollection_Limit(t *testing.T) {
|
||||||
|
status, collection := testGetCollection(t, "2", "3", "0")
|
||||||
|
assert.Equal(t, http.StatusOK, status)
|
||||||
|
assert.Equal(t, "Nouvelles", collection.Name)
|
||||||
|
assert.Equal(t, 3, len(collection.Books))
|
||||||
|
assert.Equal(t, int64(4), collection.Count)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestGetCollection_Unauthorized(t *testing.T) {
|
||||||
|
status, _ := testGetCollection(t, "4", "10", "0")
|
||||||
|
assert.Equal(t, http.StatusUnauthorized, status)
|
||||||
|
}
|
||||||
|
|
||||||
|
func testGetCollection(t *testing.T, id string, limit string, offset string) (int, dto.CollectionGet) {
|
||||||
|
return testutils.TestFetchModel[dto.CollectionGet](t, "/ws/collection/"+id, limit, offset)
|
||||||
|
}
|
||||||
@@ -44,6 +44,13 @@ type BookItemGet struct {
|
|||||||
CoverPath string `json:"coverPath"`
|
CoverPath string `json:"coverPath"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type CollectionGet struct {
|
||||||
|
Name string `json:"name"`
|
||||||
|
Count int64 `json:"count"`
|
||||||
|
Books []CollectionBookItemGet `json:"books"`
|
||||||
|
UserID uint `json:"-"`
|
||||||
|
}
|
||||||
|
|
||||||
type CollectionItemsGet struct {
|
type CollectionItemsGet struct {
|
||||||
Count int64 `json:"count"`
|
Count int64 `json:"count"`
|
||||||
Collections []CollectionItemGet `json:"collections"`
|
Collections []CollectionItemGet `json:"collections"`
|
||||||
|
|||||||
@@ -9,6 +9,4 @@ ValidationPropertyFail = "Validation failed for '%s' property."
|
|||||||
RegistrationDisabled = "Registration has been disabled on this instance."
|
RegistrationDisabled = "Registration has been disabled on this instance."
|
||||||
UserAlreadyExists = "An user with this name already exists."
|
UserAlreadyExists = "An user with this name already exists."
|
||||||
ErrorWhenCreatingUserFromStr = "Error when creating user from string %s"
|
ErrorWhenCreatingUserFromStr = "Error when creating user from string %s"
|
||||||
ISBNNotFoundBabelio = "ISBN %s not found on babelio."
|
Unauthorized = "You are not allowed to access this document."
|
||||||
BabelioParseError = "Error when parsing babelio."
|
|
||||||
BabelioFetchDescError = "Error when fetching description on babelio."
|
|
||||||
|
|||||||
@@ -9,6 +9,4 @@ ValidationPropertyFail = "La validation a échoué pour la propriété '%s'."
|
|||||||
RegistrationDisabled = "La création de nouveaux comptes a été désactivée sur cette instance."
|
RegistrationDisabled = "La création de nouveaux comptes a été désactivée sur cette instance."
|
||||||
UserAlreadyExists = "Un utilisateur avec le même nom existe déjà."
|
UserAlreadyExists = "Un utilisateur avec le même nom existe déjà."
|
||||||
ErrorWhenCreatingUserFromStr = "Erreur lors de la création de l'utilisateur %s"
|
ErrorWhenCreatingUserFromStr = "Erreur lors de la création de l'utilisateur %s"
|
||||||
ISBNNotFoundBabelio = "L'ISBN %s n'est pas sur babelio."
|
Unauthorized = "Vous n'êtes pas autorisé à accéder à cette page."
|
||||||
BabelioParseError = "Erreur en parsant babelio."
|
|
||||||
BabelioFetchDescError = "Erreur lors de la récupération de la description sur babelio."
|
|
||||||
|
|||||||
@@ -186,6 +186,7 @@ func selectBookItem() string {
|
|||||||
|
|
||||||
type CollectionsQueryResult struct {
|
type CollectionsQueryResult struct {
|
||||||
ID uint
|
ID uint
|
||||||
|
UserID uint
|
||||||
Name string
|
Name string
|
||||||
BookId uint
|
BookId uint
|
||||||
BookTitle string
|
BookTitle string
|
||||||
@@ -204,7 +205,8 @@ func FetchAllCollections(db *gorm.DB, userId uint, limit int, offset int) ([]Col
|
|||||||
return collections, res.Error
|
return collections, res.Error
|
||||||
}
|
}
|
||||||
for _, collectionId := range collectionIds {
|
for _, collectionId := range collectionIds {
|
||||||
queryResults, err := queryBooksForCollection(db, collectionId.ID)
|
//only takes first 5 books
|
||||||
|
queryResults, err := FetchCollectionBooks(db, collectionId.ID, 5, 0)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return collections, res.Error
|
return collections, res.Error
|
||||||
}
|
}
|
||||||
@@ -213,18 +215,29 @@ func FetchAllCollections(db *gorm.DB, userId uint, limit int, offset int) ([]Col
|
|||||||
return collections, res.Error
|
return collections, res.Error
|
||||||
}
|
}
|
||||||
|
|
||||||
func queryBooksForCollection(db *gorm.DB, collectionId uint) ([]CollectionsQueryResult, error) {
|
func FetchCollectionBooks(db *gorm.DB, collectionId uint, limit int, offset int) ([]CollectionsQueryResult, error) {
|
||||||
var collections []CollectionsQueryResult
|
var collections []CollectionsQueryResult
|
||||||
|
query := fetchCollectionBooksQuery(db, collectionId)
|
||||||
|
query = query.Limit(limit)
|
||||||
|
query = query.Offset(offset)
|
||||||
|
res := query.Find(&collections)
|
||||||
|
return collections, res.Error
|
||||||
|
}
|
||||||
|
|
||||||
|
func FetchCollectionBooksCount(db *gorm.DB, collectionId uint) (int64, error) {
|
||||||
|
var count int64
|
||||||
|
res := fetchCollectionBooksQuery(db, collectionId).Count(&count)
|
||||||
|
return count, res.Error
|
||||||
|
}
|
||||||
|
|
||||||
|
func fetchCollectionBooksQuery(db *gorm.DB, collectionId uint) *gorm.DB {
|
||||||
query := db.Model(&model.Collection{})
|
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.Select("collections.id, collections.user_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 collection_books on (collection_books.collection_id = collections.id)")
|
||||||
query = query.Joins("left join books on (books.id = collection_books.book_id)")
|
query = query.Joins("left join books on (books.id = collection_books.book_id)")
|
||||||
query = joinStaticFiles(query)
|
query = joinStaticFiles(query)
|
||||||
query = query.Where("collections.id = ?", collectionId)
|
query = query.Where("collections.id = ?", collectionId)
|
||||||
//only takes first 5 books
|
return query
|
||||||
query = query.Limit(5)
|
|
||||||
res := query.Find(&collections)
|
|
||||||
return collections, res.Error
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func FetchAllCollectionsCount(db *gorm.DB, userId uint) (int64, error) {
|
func FetchAllCollectionsCount(db *gorm.DB, userId uint) (int64, error) {
|
||||||
|
|||||||
61
internal/routes/collectionget.go
Normal file
61
internal/routes/collectionget.go
Normal file
@@ -0,0 +1,61 @@
|
|||||||
|
package routes
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
|
||||||
|
"git.artlef.fr/bibliomane/internal/adapter"
|
||||||
|
"git.artlef.fr/bibliomane/internal/appcontext"
|
||||||
|
"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
|
||||||
|
}
|
||||||
|
collectionBooksDb, err := query.FetchCollectionBooks(ac.Db, uint(collectionId), limit, offset)
|
||||||
|
if err != nil {
|
||||||
|
myvalidator.ReturnErrorsAsJsonResponse(&ac, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
collection := adapter.CollectionQueryToCollectionDto(collectionBooksDb)
|
||||||
|
count, err := query.FetchCollectionBooksCount(ac.Db, uint(collectionId))
|
||||||
|
if err != nil {
|
||||||
|
myvalidator.ReturnErrorsAsJsonResponse(&ac, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
collection.Count = count
|
||||||
|
if collection.UserID != user.ID {
|
||||||
|
err := myvalidator.HttpError{
|
||||||
|
StatusCode: http.StatusUnauthorized,
|
||||||
|
Err: errors.New(i18nresource.GetTranslatedMessage(&ac, "Unauthorized")),
|
||||||
|
}
|
||||||
|
myvalidator.ReturnErrorsAsJsonResponse(&ac, err)
|
||||||
|
return
|
||||||
|
} else {
|
||||||
|
ac.C.JSON(http.StatusOK, collection)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -31,7 +31,7 @@ func GetCollectionsHandler(ac appcontext.AppContext) {
|
|||||||
myvalidator.ReturnErrorsAsJsonResponse(&ac, err)
|
myvalidator.ReturnErrorsAsJsonResponse(&ac, err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
collections := adapter.CollectionQueryToDto(collectionsDb)
|
collections := adapter.CollectionQueryToCollectionItemDto(collectionsDb)
|
||||||
count, err := query.FetchAllCollectionsCount(ac.Db, user.ID)
|
count, err := query.FetchAllCollectionsCount(ac.Db, user.ID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
myvalidator.ReturnErrorsAsJsonResponse(&ac, err)
|
myvalidator.ReturnErrorsAsJsonResponse(&ac, err)
|
||||||
|
|||||||
@@ -81,6 +81,9 @@ func Setup(config *config.Config) *gin.Engine {
|
|||||||
ws.GET("/collections", func(c *gin.Context) {
|
ws.GET("/collections", func(c *gin.Context) {
|
||||||
routes.GetCollectionsHandler(appcontext.AppContext{C: c, Db: db, I18n: bundle, Config: config})
|
routes.GetCollectionsHandler(appcontext.AppContext{C: c, Db: db, I18n: bundle, Config: config})
|
||||||
})
|
})
|
||||||
|
ws.GET("/collection/:id", func(c *gin.Context) {
|
||||||
|
routes.GetCollectionHandler(appcontext.AppContext{C: c, Db: db, I18n: bundle, Config: config})
|
||||||
|
})
|
||||||
ws.POST("/collection", func(c *gin.Context) {
|
ws.POST("/collection", func(c *gin.Context) {
|
||||||
routes.PostCollectionHandler(appcontext.AppContext{C: c, Db: db, I18n: bundle, Config: config})
|
routes.PostCollectionHandler(appcontext.AppContext{C: c, Db: db, I18n: bundle, Config: config})
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -68,6 +68,23 @@ func TestBookPutCallWithDemoPayload(t *testing.T, payload string, bookId string,
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestFetchOneModel[T any](t *testing.T, urlpath string, id string) (int, T) {
|
||||||
|
router := TestSetup()
|
||||||
|
|
||||||
|
token := ConnectDemoUser(router)
|
||||||
|
req, _ := http.NewRequest("GET", urlpath+"/"+id, nil)
|
||||||
|
req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", token))
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
router.ServeHTTP(w, req)
|
||||||
|
|
||||||
|
var result T
|
||||||
|
err := json.Unmarshal(w.Body.Bytes(), &result)
|
||||||
|
if err != nil {
|
||||||
|
t.Error(err)
|
||||||
|
}
|
||||||
|
return w.Code, result
|
||||||
|
}
|
||||||
|
|
||||||
func TestFetchModel[T any](t *testing.T, urlpath string, limit string, offset string) (int, T) {
|
func TestFetchModel[T any](t *testing.T, urlpath string, limit string, offset string) (int, T) {
|
||||||
router := TestSetup()
|
router := TestSetup()
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user