preorder/orders/models.go

74 lines
1.8 KiB
Go
Raw Normal View History

2024-06-20 02:49:55 +00:00
package orders
2024-06-18 04:37:32 +00:00
2024-06-20 02:49:55 +00:00
import (
2024-06-20 03:04:59 +00:00
"encoding/json"
"io"
"net/http"
2024-06-20 02:49:55 +00:00
"preorder/authors"
"preorder/formats"
2024-06-20 03:04:59 +00:00
"strconv"
2024-06-20 02:49:55 +00:00
"time"
)
2024-06-18 04:37:32 +00:00
2024-06-20 03:04:59 +00:00
const googleBooksAPI = "https://www.googleapis.com/books/v1/volumes?q=isbn:"
2024-06-18 04:37:32 +00:00
type Order struct {
ID uint `json:"id" gorm:"primary_key"`
Title string `json:"title"`
AuthorID uint `json:"author"`
2024-06-20 02:49:55 +00:00
Author authors.Author
2024-06-18 04:37:32 +00:00
ReleaseDate time.Time `json:"release_date" gorm:"column:release_date"`
ISBN13 uint `json:"isbn_13" gorm:"column:isbn_13"`
FormatID uint `json:"format"`
2024-06-20 02:49:55 +00:00
Format formats.Format
2024-06-18 04:37:32 +00:00
}
type CreateOrderInput struct {
ID uint `json:"id" binding:"required"`
Title string `json:"title" binding:"required"`
Author uint `json:"author" binding:"required"`
Format uint `json:"format" binding:"required"`
ReleaseDate time.Time `json:"release_date"`
ISBN13 uint `json:"isbn_13" binding:"required"`
}
type UpdateOrderInput struct {
Title string `json:"title"`
}
2024-06-19 02:59:35 +00:00
2024-06-20 03:04:59 +00:00
func NewOrder(id uint, title string, author uint, format uint, isbn13 uint, releaseDate time.Time) Order {
2024-06-19 02:59:35 +00:00
order := Order{
ID: id,
Title: title,
AuthorID: author,
FormatID: format,
2024-06-20 03:04:59 +00:00
ISBN13: isbn13,
ReleaseDate: releaseDate,
2024-06-19 02:59:35 +00:00
}
return order
}
2024-06-20 03:04:59 +00:00
func (o *Order) fetchCoverImageURL() (string, error) {
resp, err := http.Get(googleBooksAPI + strconv.Itoa(int(o.ISBN13)))
if err != nil {
return "", err
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return "", err
}
var googleBooksResponse GoogleBooksResponse
if err := json.Unmarshal(body, &googleBooksResponse); err != nil {
return "", err
}
if len(googleBooksResponse.Items) > 0 {
return googleBooksResponse.Items[0].VolumeInfo.ImageLinks.Thumbnail, nil
}
return "", nil
}