61 lines
1.4 KiB
Go
61 lines
1.4 KiB
Go
package openlibrary
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
|
|
"git.artlef.fr/PersonalLibraryManager/internal/callapiutils"
|
|
)
|
|
|
|
type OpenLibraryAuthorResult struct {
|
|
Name string
|
|
Description string
|
|
}
|
|
|
|
type openLibraryParsedAuthor struct {
|
|
Name string `json:"name" binding:"required"`
|
|
Description openLibraryAuthorBio `json:"bio"`
|
|
}
|
|
|
|
type openLibraryAuthorBio struct {
|
|
Value string
|
|
}
|
|
|
|
func (b *openLibraryAuthorBio) UnmarshalJSON(data []byte) error {
|
|
var possibleFormat struct {
|
|
Type string `json:"type"`
|
|
Value string `json:"value"`
|
|
}
|
|
err := json.Unmarshal(data, &possibleFormat)
|
|
if err != nil {
|
|
//if unmarshalling failed, try to decode as string
|
|
var value string
|
|
err = json.Unmarshal(data, &value)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
b.Value = value
|
|
} else {
|
|
b.Value = possibleFormat.Value
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func CallOpenLibraryAuthor(openLibraryId string) (OpenLibraryAuthorResult, error) {
|
|
var response OpenLibraryAuthorResult
|
|
u, err := computeOpenLibraryUrl("authors", fmt.Sprintf("%s.json", openLibraryId))
|
|
if err != nil {
|
|
return response, err
|
|
}
|
|
var queryResult openLibraryParsedAuthor
|
|
err = callapiutils.FetchAndParseResult(u, &queryResult)
|
|
if err != nil {
|
|
return response, err
|
|
}
|
|
response = OpenLibraryAuthorResult{
|
|
Name: queryResult.Name,
|
|
Description: queryResult.Description.Value,
|
|
}
|
|
return response, err
|
|
}
|