-
Notifications
You must be signed in to change notification settings - Fork 0
/
api.handlers.book.go
248 lines (232 loc) · 11.6 KB
/
api.handlers.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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
package main
import (
"encoding/json"
"fmt"
"net/http"
"time"
"github.com/julienschmidt/httprouter"
"go.uber.org/zap"
)
// Index provides same details like `Status` handler by redirecting the request.
func (api *APIHandler) Index(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
http.Redirect(w, r, "/status", http.StatusSeeOther)
}
// Status provides basics details about the application to the public users.
// @Summary Get the app status
// @Description Get how long the application has been online.
// @ID get-status
// @Tags Books
// @Produce json
// @Success 200 {object} StatusResponse
// @Router /status [GET]
func (api *APIHandler) Status(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
requestID := GetValueFromContext(r.Context(), RequestIDContextKey)
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
if err := json.NewEncoder(w).Encode(
StatusResponse{
RequestID: requestID,
Status: fmt.Sprintf("up & running since %.0f mins", api.clock.Now().Sub(api.stats.started).Minutes()),
Message: "Hello. Books store api is available. Enjoy :)",
},
); err != nil {
api.logger.Error("failed to send status response", zap.String("request.id", requestID), zap.Error(err))
}
}
// CreateBook provides basics details about the application to the public users.
// @Summary Creates new book.
// @Description Creates a book submitted and returns its ID.
// @ID create-book
// @Tags Books
// @Security Bearer
// @Consume json
// @Produce json
// @Param Book body Book true "Book to create"
// @Success 201 {object} StatusResponse
// @Failure 400 {object} APIError
// @Failure 500 {object} APIError
// @Router /api/v1/books [POST]
func (api *APIHandler) CreateBook(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
book := Book{}
requestID := GetValueFromContext(r.Context(), RequestIDContextKey)
err := DecodeCreateOrUpdateBookRequestBody(r, &book)
if err != nil {
api.logger.Error("failed to create book", zap.String("request.id", requestID), zap.Error(err))
errResp := NewAPIError(requestID, http.StatusBadRequest, "failed to create the book", book)
if err = WriteErrorResponse(r.Context(), w, errResp); err != nil {
api.logger.Error("failed to send error response", zap.String("request.id", requestID), zap.Error(err))
}
return
}
err = ValidateCreateBookRequestBody(&book)
if err != nil {
api.logger.Error("failed to create book", zap.String("request.id", requestID), zap.Error(err))
errResp := NewAPIError(requestID, http.StatusBadRequest, "failed to create the book", err.Error())
if err = WriteErrorResponse(r.Context(), w, errResp); err != nil {
api.logger.Error("failed to send error response", zap.String("request.id", requestID), zap.Error(err))
}
return
}
book.ID = api.idsHandler.Generate(BookIDPrefix)
book.CreatedAt = api.clock.Now().String()
book.UpdatedAt = api.clock.Now().String()
err = api.bookService.Add(r.Context(), book.ID, book)
if err != nil {
api.logger.Error("failed to create book", zap.String("request.id", requestID), zap.Error(err))
errResp := NewAPIError(requestID, http.StatusInternalServerError, "failed to create the book", book)
if err = WriteErrorResponse(r.Context(), w, errResp); err != nil {
api.logger.Error("failed to send error response", zap.String("request.id", requestID), zap.Error(err))
}
return
}
resp := GenericResponse(requestID, http.StatusCreated, "Book created successfully.", nil, book)
if err = WriteResponse(r.Context(), w, resp); err != nil {
api.logger.Error("failed to send response", zap.String("request.id", requestID), zap.Error(err))
}
}
//nolint:bodyclose
func (api *APIHandler) GetAllBooks(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
requestID := GetValueFromContext(r.Context(), RequestIDContextKey)
// this block could be moved into the TimeoutMiddleware and remove SetWriteDeadline and
// ReadWriteDeadline methods from *CustomResponseWriter object because that middleware
// is called before the stats middleware which wraps the native ResponseWriter.
rc := http.NewResponseController(w)
if err := rc.SetWriteDeadline(time.Now().Add(api.config.Server.LongRequestWriteTimeout)); err != nil {
api.logger.Error("http: failed to update the write deadline", zap.String("request.id", requestID), zap.Error(err))
}
books, err := api.bookService.GetAll(r.Context())
if err != nil {
api.logger.Error("failed to get all books", zap.String("request.id", requestID), zap.Error(err))
errResp := NewAPIError(requestID, http.StatusInternalServerError, "failed to get all books", books)
if err = WriteErrorResponse(r.Context(), w, errResp); err != nil {
api.logger.Error("failed to send error response", zap.String("request.id", requestID), zap.Error(err))
}
return
}
api.logger.Info("success to get all books", zap.String("request.id", requestID))
total := len(books)
resp := GenericResponse(requestID, http.StatusOK, "All books fetched successfully.", &total, books)
if err = WriteResponse(r.Context(), w, resp); err != nil {
api.logger.Error("failed to send response", zap.Error(err))
}
}
func (api *APIHandler) GetOneBook(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
requestID := GetValueFromContext(r.Context(), RequestIDContextKey)
id := ps.ByName("id")
if ok := api.idsHandler.IsValid(id, BookIDPrefix); !ok {
api.logger.Error("book id provided is not valid", zap.String("book.id", id), zap.String("request.id", requestID))
errResp := NewAPIError(requestID, http.StatusBadRequest, "book id provided is not valid", Book{})
if err := WriteErrorResponse(r.Context(), w, errResp); err != nil {
api.logger.Error("failed to send error response", zap.String("request.id", requestID), zap.Error(err))
}
return
}
book, err := api.bookService.GetOne(r.Context(), id)
if err == ErrBookNotFound {
api.logger.Error("book does not exist", zap.String("book.id", id), zap.String("request.id", requestID))
errResp := NewAPIError(requestID, http.StatusNotFound, "book does not exist", book)
if err = WriteErrorResponse(r.Context(), w, errResp); err != nil {
api.logger.Error("failed to send error response", zap.String("request.id", requestID), zap.Error(err))
}
return
}
if err != nil {
api.logger.Error("failed to get book", zap.String("book.id", id), zap.String("request.id", requestID), zap.Error(err))
errResp := NewAPIError(requestID, http.StatusInternalServerError, "failed to create the book", book)
if err = WriteErrorResponse(r.Context(), w, errResp); err != nil {
api.logger.Error("failed to send error response", zap.String("request.id", requestID), zap.Error(err))
}
return
}
api.logger.Info("success to get book", zap.String("book.id", id), zap.String("request.id", requestID))
resp := GenericResponse(requestID, http.StatusOK, "Book fetched successfully.", nil, book)
if err = WriteResponse(r.Context(), w, resp); err != nil {
api.logger.Error("failed to send response", zap.String("request.id", requestID), zap.Error(err))
}
}
func (api *APIHandler) DeleteOneBook(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
requestID := GetValueFromContext(r.Context(), RequestIDContextKey)
id := ps.ByName("id")
if ok := api.idsHandler.IsValid(id, BookIDPrefix); !ok {
api.logger.Error("book id provided is not valid", zap.String("book.id", id), zap.String("request.id", requestID))
errResp := NewAPIError(requestID, http.StatusBadRequest, "book id provided is not valid", Book{})
if err := WriteErrorResponse(r.Context(), w, errResp); err != nil {
api.logger.Error("failed to send error response", zap.String("request.id", requestID), zap.Error(err))
}
return
}
book, err := api.bookService.GetOne(r.Context(), id)
if err == ErrBookNotFound {
api.logger.Error("book does not exist", zap.String("book.id", id), zap.String("request.id", requestID))
errResp := NewAPIError(requestID, http.StatusNotFound, "book does not exist", book)
if err = WriteErrorResponse(r.Context(), w, errResp); err != nil {
api.logger.Error("failed to send error response", zap.String("request.id", requestID), zap.Error(err))
}
return
}
if err != nil {
api.logger.Error("failed to check if the book exist", zap.String("book.id", id), zap.String("request.id", requestID), zap.Error(err))
errResp := NewAPIError(requestID, http.StatusInternalServerError, "failed to check if the book exist", book)
if err = WriteErrorResponse(r.Context(), w, errResp); err != nil {
api.logger.Error("failed to send error response", zap.String("request.id", requestID), zap.Error(err))
}
return
}
err = api.bookService.Delete(r.Context(), id)
if err == ErrBookNotFound {
api.logger.Error("book does not exist", zap.String("book.id", id), zap.String("request.id", requestID))
errResp := NewAPIError(requestID, http.StatusNotFound, "book does not exist", book)
if err = WriteErrorResponse(r.Context(), w, errResp); err != nil {
api.logger.Error("failed to send error response", zap.String("request.id", requestID), zap.Error(err))
}
return
}
if err != nil {
api.logger.Error("failed to delete book", zap.String("book.id", id), zap.String("request.id", requestID), zap.Error(err))
errResp := NewAPIError(requestID, http.StatusInternalServerError, "failed to delete the book", book)
if err = WriteErrorResponse(r.Context(), w, errResp); err != nil {
api.logger.Error("failed to send error response", zap.String("request.id", requestID), zap.Error(err))
}
return
}
api.logger.Info("success to delete book", zap.String("book.id", id), zap.String("request.id", requestID))
resp := GenericResponse(requestID, http.StatusOK, "Book deleted successfully.", nil, book)
if err = WriteResponse(r.Context(), w, resp); err != nil {
api.logger.Error("failed to send response", zap.String("request.id", requestID), zap.Error(err))
}
}
func (api *APIHandler) UpdateBook(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
var book Book
requestID := GetValueFromContext(r.Context(), RequestIDContextKey)
err := DecodeCreateOrUpdateBookRequestBody(r, &book)
if err != nil {
api.logger.Error("failed to update book", zap.String("request.id", requestID), zap.Error(err))
errResp := NewAPIError(requestID, http.StatusBadRequest, "failed to update the book", book)
if err = WriteErrorResponse(r.Context(), w, errResp); err != nil {
api.logger.Error("failed to send error response", zap.String("request.id", requestID), zap.Error(err))
}
return
}
err = ValidateUpdateBookRequestBody(&book)
if err != nil {
api.logger.Error("failed to update book", zap.String("request.id", requestID), zap.Error(err))
errResp := NewAPIError(requestID, http.StatusBadRequest, "failed to update the book", err.Error())
if err = WriteErrorResponse(r.Context(), w, errResp); err != nil {
api.logger.Error("failed to send error response", zap.String("request.id", requestID), zap.Error(err))
}
return
}
book, err = api.bookService.Update(r.Context(), book.ID, book)
if err != nil {
api.logger.Error("failed to update book", zap.String("request.id", requestID), zap.Error(err))
errResp := NewAPIError(requestID, http.StatusInternalServerError, "failed to update the book", book)
if err = WriteErrorResponse(r.Context(), w, errResp); err != nil {
api.logger.Error("failed to send error response", zap.String("request.id", requestID), zap.Error(err))
}
return
}
api.logger.Info("success to update book", zap.String("book.id", book.ID), zap.String("request.id", requestID))
resp := GenericResponse(requestID, http.StatusOK, "Book updated successfully.", nil, book)
if err = WriteResponse(r.Context(), w, resp); err != nil {
api.logger.Error("failed to send response", zap.String("request.id", requestID), zap.Error(err))
}
}