Author books API: use a single query with result and count

This commit is contained in:
2026-01-23 22:10:10 +01:00
parent 4ac0f4243d
commit cd2b8a93bb
6 changed files with 21 additions and 59 deletions

View File

@@ -12,6 +12,11 @@ import (
"github.com/stretchr/testify/assert"
)
type bookAuthorGetResult struct {
Count int64 `json:"count"`
Books []bookAuthorGet `json:"books"`
}
type bookAuthorGet struct {
Id uint `json:"id"`
Title string `json:"title" binding:"required,max=300"`
@@ -22,21 +27,24 @@ type bookAuthorGet struct {
}
func TestSearchBookPerAuthor_Ok(t *testing.T) {
books := testFetchBookAuthor(t, 1, "", "")
assert.Equal(t, 3, len(books))
result := testFetchBookAuthor(t, 1, "", "")
assert.Equal(t, 3, len(result.Books))
assert.Equal(t, int64(3), result.Count)
}
func TestSearchBookPerAuthor_Limit(t *testing.T) {
books := testFetchBookAuthor(t, 1, "2", "")
assert.Equal(t, 2, len(books))
result := testFetchBookAuthor(t, 1, "2", "")
assert.Equal(t, 2, len(result.Books))
assert.Equal(t, int64(2), result.Count)
}
func TestSearchBookPerAuthor_Offset(t *testing.T) {
books := testFetchBookAuthor(t, 1, "10", "2")
assert.Equal(t, 1, len(books))
result := testFetchBookAuthor(t, 1, "10", "2")
assert.Equal(t, 1, len(result.Books))
assert.Equal(t, int64(1), result.Count)
}
func testFetchBookAuthor(t *testing.T, authorId uint, limit string, offset string) []bookAuthorGet {
func testFetchBookAuthor(t *testing.T, authorId uint, limit string, offset string) bookAuthorGetResult {
router := testutils.TestSetup()
u, err := url.Parse(fmt.Sprintf("/author/%d/books", authorId))
@@ -60,12 +68,12 @@ func testFetchBookAuthor(t *testing.T, authorId uint, limit string, offset strin
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
var books []bookAuthorGet
var result bookAuthorGetResult
s := w.Body.String()
err = json.Unmarshal([]byte(s), &books)
err = json.Unmarshal([]byte(s), &result)
if err != nil {
t.Error(err)
}
assert.Equal(t, 200, w.Code)
return books
return result
}

View File

@@ -71,22 +71,3 @@ func TestGetReadingBooksCountHandler_Demo(t *testing.T) {
}
assert.Equal(t, 2, c.Count)
}
func TestGetAuthorsBooksCountHandler_Demo(t *testing.T) {
router := testutils.TestSetup()
token := testutils.ConnectDemoUser(router)
req, _ := http.NewRequest("GET", "/author/1/books/count", nil)
req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", token))
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
var c countResponse
err := json.Unmarshal(w.Body.Bytes(), &c)
if err != nil {
t.Error(err)
}
assert.Equal(t, 3, c.Count)
}