Add pagination for booksearch
This commit is contained in:
@@ -1,5 +1,6 @@
|
||||
<script setup>
|
||||
import { computed } from 'vue'
|
||||
|
||||
import { ref, computed } from 'vue'
|
||||
import { getBook, getImagePathOrDefault, putReadBook, putWantReadBook, putRateBook } from './api.js'
|
||||
import { onBeforeRouteUpdate } from 'vue-router'
|
||||
import { VRating } from 'vuetify/components/VRating';
|
||||
@@ -9,12 +10,12 @@
|
||||
id: String
|
||||
});
|
||||
|
||||
let { data, error } = getBook(props.id);
|
||||
let data = ref(null);
|
||||
let error = ref(null);
|
||||
getBook(data, error, props.id);
|
||||
const imagePathOrDefault = computed(() => getImagePathOrDefault(data.value.coverPath));
|
||||
onBeforeRouteUpdate(async (to, from) => {
|
||||
let res = getBook(to.params.id);
|
||||
data = res.data;
|
||||
error = res.error;
|
||||
getBook(data, error, to.params.id);
|
||||
})
|
||||
|
||||
function onRatingUpdate(rating) {
|
||||
|
||||
@@ -18,23 +18,20 @@ const offset = computed(() => (pageNumber.value - 1) * limit);
|
||||
|
||||
let currentFilterState = ref(FilterStates.READ);
|
||||
|
||||
let data;
|
||||
let error;
|
||||
let totalBooksData;
|
||||
let errorFetchTotal;
|
||||
let data = ref(null);
|
||||
let error = ref(null);
|
||||
let totalBooksData = ref(null);
|
||||
let errorFetchTotal = ref(null);
|
||||
|
||||
let totalBooksNumber = computed(() => totalBooksData ? totalBooksData.value["count"] : 0);
|
||||
let totalBooksNumber = computed(() => (typeof(totalBooksData) != 'undefined' &&
|
||||
totalBooksData.value != null) ? totalBooksData.value["count"] : 0);
|
||||
let pageTotal = computed(() => Math.ceil(totalBooksNumber.value / limit))
|
||||
|
||||
fetchData();
|
||||
|
||||
function fetchData() {
|
||||
let res = getMyBooks(currentFilterState.value, limit, offset.value);
|
||||
data = res.data;
|
||||
error = res.error;
|
||||
let resCount = getCountMyBooks(currentFilterState.value);
|
||||
totalBooksData = resCount.data;
|
||||
|
||||
let res = getMyBooks(data, error, currentFilterState.value, limit, offset.value);
|
||||
let resCount = getCountMyBooks(totalBooksData, errorFetchTotal, currentFilterState.value);
|
||||
}
|
||||
|
||||
function onFilterButtonClick(newstate) {
|
||||
@@ -48,7 +45,7 @@ function computeDynamicClass(state) {
|
||||
|
||||
function pageChange(newPageNumber) {
|
||||
pageNumber.value = newPageNumber;
|
||||
data.value = null
|
||||
data.value = null;
|
||||
fetchData();
|
||||
}
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
if (typeof searchterm.value === "undefined" || searchterm.value === "") {
|
||||
return
|
||||
}
|
||||
router.push('/search/' + searchterm.value);
|
||||
router.push('/search/' + encodeURIComponent(searchterm.value));
|
||||
}
|
||||
</script>
|
||||
|
||||
|
||||
@@ -48,7 +48,7 @@
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<nav class="pagination" role="navigation" aria-label="pagination">
|
||||
<nav v-if="props.pageTotal > 1" class="pagination" role="navigation" aria-label="pagination">
|
||||
<a href="#" v-if="props.pageNumber > 1"
|
||||
@click="$emit('pageChange', Math.max(1, props.pageNumber - 1))"
|
||||
class="pagination-previous">
|
||||
|
||||
@@ -1,27 +1,62 @@
|
||||
<script setup>
|
||||
import { ref, computed } from 'vue'
|
||||
import BookListElement from './BookListElement.vue';
|
||||
import { getSearchBooks } from './api.js'
|
||||
import { getSearchBooks, getCountSearchBooks } from './api.js'
|
||||
import { onBeforeRouteUpdate } from 'vue-router'
|
||||
import Pagination from './Pagination.vue'
|
||||
|
||||
const limit = 5;
|
||||
const pageNumber = ref(1);
|
||||
|
||||
const offset = computed(() => (pageNumber.value - 1) * limit);
|
||||
|
||||
const props = defineProps({
|
||||
searchterm: String
|
||||
});
|
||||
|
||||
let { data, error } = getSearchBooks(props.searchterm);
|
||||
let data = ref(null);
|
||||
let error = ref(null);
|
||||
let totalBooksData = ref(null);
|
||||
let errorFetchTotal = ref(null);
|
||||
|
||||
const pageTotal = computed(() => {
|
||||
let countValue = totalBooksData.value !== null ? totalBooksData.value['count'] : 0;
|
||||
return Math.ceil(countValue / limit);
|
||||
});
|
||||
|
||||
fetchData(props.searchterm);
|
||||
|
||||
|
||||
function fetchData(searchTerm) {
|
||||
getSearchBooks(data, error, searchTerm, limit, offset.value);
|
||||
getCountSearchBooks(totalBooksData, errorFetchTotal, searchTerm);
|
||||
}
|
||||
|
||||
onBeforeRouteUpdate(async (to, from) => {
|
||||
let res = getSearchBooks(to.params.searchterm);
|
||||
data = res.data;
|
||||
error = res.error;
|
||||
pageNumber.value = 1;
|
||||
fetchData(to.params.searchterm);
|
||||
})
|
||||
|
||||
function pageChange(newPageNumber) {
|
||||
pageNumber.value = newPageNumber;
|
||||
data.value = null;
|
||||
fetchData(props.searchterm);
|
||||
}
|
||||
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="booksearch">
|
||||
<div v-if="error">{{$t('searchbook.error', {error: error.message})}}</div>
|
||||
<div class="booksearchlist" v-else-if="data && data.length > 0" v-for="book in data" :key="book.id">
|
||||
<BookListElement v-bind="book" />
|
||||
<div v-else-if="data && data.length > 0">
|
||||
<div class="booksearchlist" v-for="book in data" :key="book.id">
|
||||
<BookListElement v-bind="book" />
|
||||
</div>
|
||||
<Pagination
|
||||
:pageNumber="pageNumber"
|
||||
:pageTotal="pageTotal"
|
||||
maxItemDisplayed="11"
|
||||
@pageChange="pageChange"/>
|
||||
</div>
|
||||
<div v-else-if="data === null">{{$t('searchbook.loading')}}</div>
|
||||
<div v-else>{{$t('searchbook.noresult')}}</div>
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import { ref } from 'vue'
|
||||
import { useAuthStore } from './auth.store.js'
|
||||
|
||||
const baseUrl = "http://localhost:8080"
|
||||
@@ -8,10 +7,7 @@ export function getImagePathOrDefault(path) {
|
||||
"../defaultbook.png" : baseUrl + path;
|
||||
}
|
||||
|
||||
function useFetch(url) {
|
||||
const data = ref(null);
|
||||
const error = ref(null);
|
||||
|
||||
function useFetch(data, error, url) {
|
||||
const { user } = useAuthStore();
|
||||
|
||||
if (user != null) {
|
||||
@@ -25,25 +21,28 @@ function useFetch(url) {
|
||||
.then((json) => (data.value = json))
|
||||
.catch((err) => (error.value = err));
|
||||
}
|
||||
|
||||
return { data, error }
|
||||
}
|
||||
|
||||
export function getCountMyBooks(arg) {
|
||||
return useFetch(baseUrl + '/mybooks/' + arg + "/count");
|
||||
export function getCountMyBooks(data, error, arg) {
|
||||
return useFetch(data, error, baseUrl + '/mybooks/' + arg + "/count");
|
||||
}
|
||||
|
||||
export function getMyBooks(arg, limit, offset) {
|
||||
export function getMyBooks(data, error, arg, limit, offset) {
|
||||
const queryParams = new URLSearchParams({limit: limit, offset: offset});
|
||||
return useFetch(baseUrl + '/mybooks/' + arg + "?" + queryParams.toString());
|
||||
return useFetch(data, error, baseUrl + '/mybooks/' + arg + "?" + queryParams.toString());
|
||||
}
|
||||
|
||||
export function getSearchBooks(searchterm) {
|
||||
return useFetch(baseUrl + '/search/' + searchterm);
|
||||
export function getCountSearchBooks(data, error, searchterm) {
|
||||
return useFetch(data, error,baseUrl + '/search/' + encodeURIComponent(searchterm) + '/count')
|
||||
}
|
||||
|
||||
export function getBook(id) {
|
||||
return useFetch(baseUrl + '/book/' + id);
|
||||
export function getSearchBooks(data, error, searchterm, limit, offset) {
|
||||
const queryParams = new URLSearchParams({limit: limit, offset: offset});
|
||||
return useFetch(data, error, baseUrl + '/search/' + encodeURIComponent(searchterm) + "?" + queryParams.toString());
|
||||
}
|
||||
|
||||
export function getBook(data, error, id) {
|
||||
return useFetch(data, error, baseUrl + '/book/' + id);
|
||||
}
|
||||
|
||||
export function postBook(book) {
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"testing"
|
||||
|
||||
"git.artlef.fr/PersonalLibraryManager/internal/testutils"
|
||||
@@ -19,33 +20,96 @@ type bookSearchGet struct {
|
||||
}
|
||||
|
||||
func TestSearchBook_MultipleBooks(t *testing.T) {
|
||||
books := testSearchBook(t, "san")
|
||||
books := testSearchBook(t, "san", "", "")
|
||||
|
||||
assert.Equal(t, 2, len(books))
|
||||
}
|
||||
|
||||
func TestSearchBook_AllFields(t *testing.T) {
|
||||
books := testSearchBook(t, "de san")
|
||||
books := testSearchBook(t, "de san", "", "")
|
||||
assert.Equal(t, 1, len(books))
|
||||
assert.Equal(t,
|
||||
[]bookSearchGet{{Title: "De sang-froid", Author: "Truman Capote", Id: 18}},
|
||||
books)
|
||||
}
|
||||
|
||||
func testSearchBook(t *testing.T, searchterm string) []bookSearchGet {
|
||||
func TestSearchBook_Limit(t *testing.T) {
|
||||
books := testSearchBook(t, "a", "10", "")
|
||||
assert.Equal(t, 10, len(books))
|
||||
}
|
||||
|
||||
func TestSearchBook_Offset(t *testing.T) {
|
||||
books := testSearchBook(t, "sa", "", "2")
|
||||
assert.Equal(t, 3, len(books))
|
||||
}
|
||||
|
||||
func testSearchBook(t *testing.T, searchterm string, limit string, offset string) []bookSearchGet {
|
||||
router := testutils.TestSetup()
|
||||
|
||||
u, err := url.Parse("/search/" + searchterm)
|
||||
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()
|
||||
}
|
||||
|
||||
token := testutils.ConnectDemoUser(router)
|
||||
req, _ := http.NewRequest("GET", "/search/"+searchterm, nil)
|
||||
req, _ := http.NewRequest("GET", u.String(), nil)
|
||||
req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", token))
|
||||
w := httptest.NewRecorder()
|
||||
router.ServeHTTP(w, req)
|
||||
|
||||
var books []bookSearchGet
|
||||
err := json.Unmarshal(w.Body.Bytes(), &books)
|
||||
err = json.Unmarshal(w.Body.Bytes(), &books)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
assert.Equal(t, 200, w.Code)
|
||||
return books
|
||||
}
|
||||
|
||||
func TestSearchBookCount_OK(t *testing.T) {
|
||||
router := testutils.TestSetup()
|
||||
|
||||
token := testutils.ConnectDemoUser(router)
|
||||
req, _ := http.NewRequest("GET", "/search/sa/count", nil)
|
||||
req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", token))
|
||||
w := httptest.NewRecorder()
|
||||
router.ServeHTTP(w, req)
|
||||
|
||||
var count countResponse
|
||||
|
||||
assert.Equal(t, 200, w.Code)
|
||||
err := json.Unmarshal(w.Body.Bytes(), &count)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
assert.Equal(t, 5, count.Count)
|
||||
}
|
||||
|
||||
func TestSearchBookCount_Zero(t *testing.T) {
|
||||
router := testutils.TestSetup()
|
||||
|
||||
token := testutils.ConnectDemoUser(router)
|
||||
req, _ := http.NewRequest("GET", "/search/dsfsfdsdfsfd/count", nil)
|
||||
req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", token))
|
||||
w := httptest.NewRecorder()
|
||||
router.ServeHTTP(w, req)
|
||||
|
||||
var count countResponse
|
||||
|
||||
assert.Equal(t, 200, w.Code)
|
||||
err := json.Unmarshal(w.Body.Bytes(), &count)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
assert.Equal(t, 0, count.Count)
|
||||
}
|
||||
|
||||
@@ -36,14 +36,28 @@ type BookSearchGet struct {
|
||||
CoverPath string `json:"coverPath"`
|
||||
}
|
||||
|
||||
func FetchBookSearchGet(db *gorm.DB, searchterm string) ([]BookSearchGet, error) {
|
||||
func FetchBookSearchGet(db *gorm.DB, searchterm string, limit int, offset int) ([]BookSearchGet, error) {
|
||||
var books []BookSearchGet
|
||||
query := fetchBookSearchQuery(db, searchterm)
|
||||
query = query.Limit(limit)
|
||||
query = query.Offset(offset)
|
||||
res := query.Find(&books)
|
||||
return books, res.Error
|
||||
}
|
||||
|
||||
func FetchBookSearchGetCount(db *gorm.DB, searchterm string) (int64, error) {
|
||||
query := fetchBookSearchQuery(db, searchterm)
|
||||
var count int64
|
||||
res := query.Count(&count)
|
||||
return count, res.Error
|
||||
}
|
||||
|
||||
func fetchBookSearchQuery(db *gorm.DB, searchterm string) *gorm.DB {
|
||||
query := db.Model(&model.Book{})
|
||||
query = query.Select("books.title, books.author, books.id," + selectStaticFilesPath())
|
||||
query = query.Joins("left join static_files on (static_files.id = books.cover_id)")
|
||||
query = query.Where("LOWER(title) LIKE ?", "%"+strings.ToLower(searchterm)+"%")
|
||||
res := query.Find(&books)
|
||||
return books, res.Error
|
||||
return query
|
||||
}
|
||||
|
||||
type BookUserGet struct {
|
||||
|
||||
@@ -6,14 +6,36 @@ import (
|
||||
"git.artlef.fr/PersonalLibraryManager/internal/appcontext"
|
||||
"git.artlef.fr/PersonalLibraryManager/internal/myvalidator"
|
||||
"git.artlef.fr/PersonalLibraryManager/internal/query"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func GetSearchBooksHandler(ac appcontext.AppContext) {
|
||||
searchterm := ac.C.Param("searchterm")
|
||||
books, err := query.FetchBookSearchGet(ac.Db, searchterm)
|
||||
|
||||
limit, err := ac.GetQueryLimit()
|
||||
if err != nil {
|
||||
myvalidator.ReturnErrorsAsJsonResponse(&ac, err)
|
||||
return
|
||||
}
|
||||
offset, err := ac.GetQueryOffset()
|
||||
if err != nil {
|
||||
myvalidator.ReturnErrorsAsJsonResponse(&ac, err)
|
||||
return
|
||||
}
|
||||
books, err := query.FetchBookSearchGet(ac.Db, searchterm, limit, offset)
|
||||
if err != nil {
|
||||
myvalidator.ReturnErrorsAsJsonResponse(&ac, err)
|
||||
return
|
||||
}
|
||||
ac.C.JSON(http.StatusOK, books)
|
||||
}
|
||||
|
||||
func GetSearchBooksCountHandler(ac appcontext.AppContext) {
|
||||
searchterm := ac.C.Param("searchterm")
|
||||
count, err := query.FetchBookSearchGetCount(ac.Db, searchterm)
|
||||
if err != nil {
|
||||
myvalidator.ReturnErrorsAsJsonResponse(&ac, err)
|
||||
return
|
||||
}
|
||||
ac.C.JSON(http.StatusOK, gin.H{"count": count})
|
||||
}
|
||||
|
||||
@@ -39,6 +39,9 @@ func Setup(config *config.Config) *gin.Engine {
|
||||
r.GET("/search/:searchterm", func(c *gin.Context) {
|
||||
routes.GetSearchBooksHandler(appcontext.AppContext{C: c, Db: db, I18n: bundle, Config: config})
|
||||
})
|
||||
r.GET("/search/:searchterm/count", func(c *gin.Context) {
|
||||
routes.GetSearchBooksCountHandler(appcontext.AppContext{C: c, Db: db, I18n: bundle, Config: config})
|
||||
})
|
||||
r.GET("/book/:id", func(c *gin.Context) {
|
||||
routes.GetBookHandler(appcontext.AppContext{C: c, Db: db, I18n: bundle, Config: config})
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user