/
endpoints.go
80 lines (72 loc) · 2.25 KB
/
endpoints.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
package bookssvc
import (
"context"
"time"
"github.com/go-kit/kit/endpoint"
)
// Book represents a single book record
type Book struct {
ID int `json:"id"`
Title string `json:"title"`
Author string `json:"author"`
AverageRating float32 `json:"average_rating"`
ISBN string `json:"isbn"`
ISBN13 string `json:"isbn13"`
LanguageCode string `json:"language_code"`
NumPages int `json:"num_pages"`
RatingsCount int `json:"ratings_count"`
TextReviewsCount int `json:"text_reviews_count"`
PublicationDate time.Time `json:"publication_date"`
Publisher string `json:"publisher"`
}
// BookService is a CRUD interface for books
type BooksService interface {
PostBook(ctx context.Context, b Book) (int, error)
GetBook(ctx context.Context, id int) (Book, error)
PutBook(ctx context.Context, id int, b Book) error
DeleteBook(ctx context.Context, id int) error
}
//
func MakePostBookEndpoint(svc BooksService) endpoint.Endpoint {
return func(ctx context.Context, request interface{}) (interface{}, error) {
req := request.(PostBookRequest)
id, err := svc.PostBook(ctx, req.Book)
if err != nil {
return ErrorResponse{Error: err.Error()}, nil
}
return PostBookResponse{ID: id}, nil
}
}
//
func MakeGetBookENdpoint(svc BooksService) endpoint.Endpoint {
return func(ctx context.Context, request interface{}) (interface{}, error) {
req := request.(GetBookRequest)
book, err := svc.GetBook(ctx, req.ID)
if err != nil {
return ErrorResponse{Error: err.Error()}, nil
}
return GetBookResponse{Book: book}, nil
}
}
//
func MakePutBookEndpoint(svc BooksService) endpoint.Endpoint {
return func(ctx context.Context, request interface{}) (interface{}, error) {
req := request.(PutBookRequest)
err := svc.PutBook(ctx, req.ID, req.Book)
if err != nil {
return ErrorResponse{Error: err.Error()}, nil
}
return nil, nil
}
}
//
func MakeDeleteBookENdpoint(svc BooksService) endpoint.Endpoint {
return func(ctx context.Context, request interface{}) (interface{}, error) {
req := request.(DeleteBookRequest)
err := svc.DeleteBook(ctx, req.ID)
if err != nil {
return ErrorResponse{Error: err.Error()}, nil
}
return nil, nil
}
}