-
Notifications
You must be signed in to change notification settings - Fork 0
/
book.go
85 lines (69 loc) · 1.67 KB
/
book.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package books
import (
"encoding/json"
"errors"
"fmt"
"strings"
)
const (
CategoryNovel = "CategoryNovel"
CategoryShortStory = "CategoryShortStory"
)
var (
ErrInvalidJSON = errors.New("JSON is invalid")
ErrIncompleteJSON = errors.New("JSON is incomplete")
)
type Book struct {
Title string `json:"title"`
Author string `json:"author"`
Pages int `json:"pages"`
}
func (b *Book) AuthorFirstName() string {
// Assuming author's name is composed by: "firstName lastName"
nameAndLastName := strings.Split(b.Author, " ")
if len(nameAndLastName) < 2 {
return ""
}
return nameAndLastName[0]
}
func (b *Book) AuthorLastName() string {
// Assuming author's name is composed by: "firstName lastName"
nameAndLastName := strings.Split(b.Author, " ")
if len(nameAndLastName) < 2 {
return nameAndLastName[0]
}
return nameAndLastName[len(nameAndLastName)-1]
}
func (b *Book) IsValid() bool {
return b.Author != ""
}
func (b *Book) Category() string {
if b.Pages > 300 {
return CategoryNovel
} else {
return CategoryShortStory
}
}
func (b *Book) AsJSON() (string, error) {
jsonData, err := json.Marshal(b)
if err != nil {
return "", fmt.Errorf("error encoding to JSON: %w", err)
}
return string(jsonData), nil
}
func NewBookFromJSON(data string) (*Book, error) {
var book Book
err := json.Unmarshal([]byte(data), &book)
if err != nil {
var syntaxErr *json.SyntaxError
if errors.As(err, &syntaxErr) {
return nil, ErrInvalidJSON
}
return nil, fmt.Errorf("error decoding from JSON: %w", err)
}
// Check for required fields
if book.Title == "" || book.Author == "" || book.Pages == 0 {
return nil, ErrIncompleteJSON
}
return &book, nil
}