Add open library API call when search has no result

This commit is contained in:
2025-12-27 01:23:40 +01:00
parent 746f6312b1
commit 167e711649
7 changed files with 1261 additions and 20 deletions

View File

@@ -7,6 +7,7 @@
const props = defineProps({ const props = defineProps({
id: Number, id: Number,
openlibraryid: String,
title: String, title: String,
author: String, author: String,
rating: Number, rating: Number,
@@ -27,7 +28,11 @@ async function onUserBookRead() {
} }
function openBook() { function openBook() {
router.push(`/book/${props.id}`) if (props.id != 0) {
router.push(`/book/${props.id}`);
} else {
console.log("Open Library Id : " + props.openlibraryid);
}
} }
</script> </script>

View File

@@ -4,13 +4,14 @@ import "gorm.io/gorm"
type Book struct { type Book struct {
gorm.Model gorm.Model
Title string `json:"title" gorm:"not null"` Title string `json:"title" gorm:"not null"`
ISBN string `json:"isbn"` ISBN string `json:"isbn"`
Summary string `json:"summary"` OpenLibraryId string `json:"openlibraryid"`
Author Author Summary string `json:"summary"`
AuthorID uint Author Author
AddedBy User AuthorID uint
AddedByID uint AddedBy User
Cover StaticFile AddedByID uint
CoverID uint Cover StaticFile
CoverID uint
} }

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,70 @@
package openlibrary
import (
"encoding/json"
"io"
"net/http"
"net/url"
"strconv"
"strings"
)
type OpenLibraryQueryResult struct {
Books []OpenLibraryBook `json:"docs"`
NumFound int `json:"numFound"`
}
type OpenLibraryBook struct {
Title string `json:"title"`
Authors []string `json:"author_name"`
OpenLibraryId string `json:"cover_edition_key"`
}
func CallOpenLibrary(searchterm string, limit int, offset int) (OpenLibraryQueryResult, error) {
var queryResult OpenLibraryQueryResult
baseUrl := "https://openlibrary.org"
booksApiUrl := "search.json"
u, err := url.Parse(baseUrl)
if err != nil {
return queryResult, err
}
u = u.JoinPath(booksApiUrl)
if limit != 0 {
addQueryParamInt(u, "limit", limit)
}
if offset != 0 {
addQueryParamInt(u, "offset", offset)
}
addQueryParam(u, "q", searchterm)
client := &http.Client{}
req, err := http.NewRequest("GET", u.String(), nil)
if err != nil {
return queryResult, err
}
req.Header.Add("Accept", "application/json")
req.Header.Add("User-Agent", "PersonalLibraryManager/0.1 (artlef@protonmail.com)")
resp, err := client.Do(req)
if err != nil {
return queryResult, err
}
defer resp.Body.Close()
bodyBytes, err := io.ReadAll(resp.Body)
if err != nil {
return queryResult, err
}
bodyString := string(bodyBytes)
decoder := json.NewDecoder(strings.NewReader(bodyString))
err = decoder.Decode(&queryResult)
return queryResult, err
}
func addQueryParamInt(u *url.URL, paramName string, paramValue int) {
addQueryParam(u, paramName, strconv.Itoa(paramValue))
}
func addQueryParam(u *url.URL, paramName string, paramValue string) {
q := u.Query()
q.Set(paramName, paramValue)
u.RawQuery = q.Encode()
}

View File

@@ -0,0 +1,27 @@
package openlibrary_test
import (
"testing"
"git.artlef.fr/PersonalLibraryManager/internal/openlibrary"
"github.com/stretchr/testify/assert"
)
func TestCallOpenLibrary(t *testing.T) {
result, err := openlibrary.CallOpenLibrary("man in high castle", 0, 0)
assert.Nil(t, err)
assert.Equal(t, result.NumFound, 25)
assert.Equal(t, len(result.Books), 25)
}
func TestCallOpenLibraryLimit(t *testing.T) {
result, err := openlibrary.CallOpenLibrary("man in high castle", 10, 0)
assert.Nil(t, err)
assert.Equal(t, len(result.Books), 10)
}
func TestCallOpenLibraryOffset(t *testing.T) {
result, err := openlibrary.CallOpenLibrary("man in high castle", 0, 10)
assert.Nil(t, err)
assert.Equal(t, len(result.Books), 15)
}

View File

@@ -9,13 +9,14 @@ import (
) )
type BookSearchGet struct { type BookSearchGet struct {
ID uint `json:"id"` ID uint `json:"id"`
Title string `json:"title" binding:"required,max=300"` Title string `json:"title" binding:"required,max=300"`
Author string `json:"author" binding:"max=100"` Author string `json:"author" binding:"max=100"`
Rating int `json:"rating"` OpenLibraryId string `json:"openlibraryid"`
Read bool `json:"read"` Rating int `json:"rating"`
WantRead bool `json:"wantread"` Read bool `json:"read"`
CoverPath string `json:"coverPath"` WantRead bool `json:"wantread"`
CoverPath string `json:"coverPath"`
} }
func FetchBookSearchByAuthorGet(db *gorm.DB, userId uint, authorId uint64, limit int, offset int) ([]BookSearchGet, error) { func FetchBookSearchByAuthorGet(db *gorm.DB, userId uint, authorId uint64, limit int, offset int) ([]BookSearchGet, error) {
@@ -69,7 +70,7 @@ func fetchBookSearchQuery(db *gorm.DB, userId uint, searchterm string) *gorm.DB
func fetchBookSearchQueryBuilder(db *gorm.DB, userId uint) *gorm.DB { func fetchBookSearchQueryBuilder(db *gorm.DB, userId uint) *gorm.DB {
query := db.Model(&model.Book{}) query := db.Model(&model.Book{})
query = query.Select("books.id, books.title, authors.name as author, user_books.rating, user_books.read, user_books.want_read, " + selectStaticFilesPath()) query = query.Select("books.id, books.title, authors.name as author, books.open_library_id, user_books.rating, user_books.read, user_books.want_read, " + selectStaticFilesPath())
query = joinAuthors(query) query = joinAuthors(query)
query = query.Joins("left join user_books on (user_books.book_id = books.id and user_books.user_id = ?)", userId) query = query.Joins("left join user_books on (user_books.book_id = books.id and user_books.user_id = ?)", userId)
query = joinStaticFiles(query) query = joinStaticFiles(query)

View File

@@ -5,6 +5,7 @@ import (
"git.artlef.fr/PersonalLibraryManager/internal/appcontext" "git.artlef.fr/PersonalLibraryManager/internal/appcontext"
"git.artlef.fr/PersonalLibraryManager/internal/myvalidator" "git.artlef.fr/PersonalLibraryManager/internal/myvalidator"
"git.artlef.fr/PersonalLibraryManager/internal/openlibrary"
"git.artlef.fr/PersonalLibraryManager/internal/query" "git.artlef.fr/PersonalLibraryManager/internal/query"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
) )
@@ -33,7 +34,36 @@ func GetSearchBooksHandler(ac appcontext.AppContext) {
myvalidator.ReturnErrorsAsJsonResponse(&ac, err) myvalidator.ReturnErrorsAsJsonResponse(&ac, err)
return return
} }
ac.C.JSON(http.StatusOK, books) var returnedBooks []query.BookSearchGet
if len(books) > 0 {
returnedBooks = books
} else {
queryResult, err := openlibrary.CallOpenLibrary(searchterm, limit, offset)
if err != nil {
myvalidator.ReturnErrorsAsJsonResponse(&ac, err)
return
}
returnedBooks = OpenLibraryBooksToBookSearchGet(queryResult.Books)
}
ac.C.JSON(http.StatusOK, returnedBooks)
}
func OpenLibraryBooksToBookSearchGet(OLbooks []openlibrary.OpenLibraryBook) []query.BookSearchGet {
var books []query.BookSearchGet
for _, b := range OLbooks {
bookSearchGet := query.BookSearchGet{
ID: 0,
Title: b.Title,
Author: b.Authors[0],
OpenLibraryId: b.OpenLibraryId,
Rating: 0,
Read: false,
WantRead: false,
CoverPath: "",
}
books = append(books, bookSearchGet)
}
return books
} }
func GetSearchBooksCountHandler(ac appcontext.AppContext) { func GetSearchBooksCountHandler(ac appcontext.AppContext) {
@@ -49,5 +79,16 @@ func GetSearchBooksCountHandler(ac appcontext.AppContext) {
myvalidator.ReturnErrorsAsJsonResponse(&ac, err) myvalidator.ReturnErrorsAsJsonResponse(&ac, err)
return return
} }
ac.C.JSON(http.StatusOK, gin.H{"count": count}) var finalCount int64
if count > 0 {
finalCount = count
} else {
queryResult, err := openlibrary.CallOpenLibrary(searchterm, 0, 0)
if err != nil {
myvalidator.ReturnErrorsAsJsonResponse(&ac, err)
return
}
finalCount = int64(queryResult.NumFound)
}
ac.C.JSON(http.StatusOK, gin.H{"count": finalCount})
} }