-
Notifications
You must be signed in to change notification settings - Fork 0
/
book.go
53 lines (44 loc) · 1.98 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
package model
import (
"errors"
"net/http"
"github.com/mongodb/mongo-go-driver/bson/objectid"
)
// Book book model structure
type Book struct {
ID objectid.ObjectID `bson:"_id,omitempty" json:"_id,omitempty"`
Author string `bson:"author" json:"author"`
Genre string `bson:"genre" json:"genre"`
NumberOfPages int64 `bson:"number_of_pages" json:"number_of_pages"`
YearOfPublication int64 `bson:"publication_year" json:"publication_year"`
Rating int64 `bson:"rating" json:"rating"`
}
// BookFilter book filter model structure
type BookFilter struct {
ID objectid.ObjectID `bson:"_id,omitempty" json:"_id,omitempty"`
Author string `bson:"author" json:"author"`
Genre string `bson:"genre" json:"genre"`
NumberOfPages int64 `bson:"number_of_pages" json:"number_of_pages"`
YearOfPublication int64 `bson:"publication_year" json:"publication_year"`
Rating int64 `bson:"rating" json:"rating"`
}
// BookRequest small hack to protect ID of being posted and update from body payload
type BookRequest struct {
*Book
ProtectedID string `json:"_id"` // override '_id' json to have more control
}
// Bind bind body into book struct
func (b *BookRequest) Bind(r *http.Request) error {
// b.Book is nil if no Book fields are sent in the request. Return an
// error to avoid a nil pointer dereference.
if b.Book == nil {
return errors.New("missing required Book fields.")
}
// b.User is nil if no Userpayload fields are sent in the request. In this app
// this won't cause a panic, but checks in this Bind method may be required if
// b.User or futher nested fields like b.User.Name are accessed elsewhere.
// just a post-process after a decode..
b.ProtectedID = "" // unset the protected ID
// b.Book.Title = strings.ToLower(b.Book.Title) // as an example, we down-case
return nil
}