Open Library search API

If nothing is found on the server, returns results from open library
API. Clicking on a book imports it.
This commit is contained in:
2025-12-30 18:13:11 +01:00
parent 4d901ccc02
commit 1bb841332c
18 changed files with 478 additions and 57 deletions

View File

@@ -15,6 +15,7 @@ type fetchedBook struct {
Title string `json:"title" binding:"required,max=300"`
Author string `json:"author" binding:"max=100"`
ISBN string `json:"isbn"`
OpenLibraryId string `json:"openlibraryid"`
Summary string `json:"summary"`
Rating int `json:"rating"`
Read bool `json:"read"`

View File

@@ -0,0 +1,66 @@
package apitest
import (
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"strconv"
"strings"
"testing"
"git.artlef.fr/PersonalLibraryManager/internal/testutils"
"github.com/stretchr/testify/assert"
)
type hasId struct {
ID uint `json:"id"`
}
func TestPostImportBookHandler_Ok(t *testing.T) {
id := testPostImportBookHandler(t, "OL21177W", http.StatusOK)
book := testGetBook(t, strconv.FormatUint(uint64(id), 10), 200)
assert.Equal(t, "Wuthering Heights", book.Title)
assert.Equal(t, "Emily Brontë", book.Author)
assert.Equal(t, "OL21177W", book.OpenLibraryId)
}
func TestPostImportBookHandler_OkAuthorKey(t *testing.T) {
id := testPostImportBookHandler(t, "OL7525169M", http.StatusOK)
book := testGetBook(t, strconv.FormatUint(uint64(id), 10), 200)
assert.Equal(t, "Dr. Bloodmoney, or How We Got Along After the Bomb", book.Title)
assert.Equal(t, "Philip K. Dick", book.Author)
assert.Equal(t, "OL7525169M", book.OpenLibraryId)
}
func TestPostImportBookHandler_NoOLID(t *testing.T) {
testPostImportBookHandler(t, "", http.StatusBadRequest)
}
func testPostImportBookHandler(t *testing.T, openlibraryid string, expectedCode int) uint {
router := testutils.TestSetup()
w := httptest.NewRecorder()
token := testutils.ConnectDemoUser(router)
queryJson := `{
"openlibraryid":"%s"
}`
queryJson = fmt.Sprintf(queryJson, openlibraryid)
req, _ := http.NewRequest("POST", "/importbook",
strings.NewReader(string(queryJson)))
req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", token))
router.ServeHTTP(w, req)
assert.Equal(t, expectedCode, w.Code)
if w.Code == 200 {
var parsedId hasId
err := json.Unmarshal(w.Body.Bytes(), &parsedId)
if err != nil {
t.Error(err)
}
return parsedId.ID
} else {
return 0
}
}