apps/library/handlers_api.go 1.0 K raw
1
package main
2
3
import (
4
	"net/http"
5
6
	"github.com/stevedylandev/andromeda/pkg/web"
7
)
8
9
func (a *App) apiListBooks(w http.ResponseWriter, r *http.Request) {
10
	status := r.URL.Query().Get("status")
11
	switch status {
12
	case "", "all":
13
		status = ""
14
	default:
15
		if !validStatus(status) {
16
			web.WriteError(w, http.StatusBadRequest, "invalid status")
17
			return
18
		}
19
	}
20
	books, err := listBooks(a.DB, status)
21
	if err != nil {
22
		a.Log.Error("list books", "err", err)
23
		w.WriteHeader(http.StatusInternalServerError)
24
		return
25
	}
26
	if books == nil {
27
		books = []Book{}
28
	}
29
	web.WriteJSON(w, http.StatusOK, books)
30
}
31
32
func (a *App) apiGetBook(w http.ResponseWriter, r *http.Request) {
33
	id, ok := web.PathInt64(r, "id")
34
	if !ok {
35
		web.WriteError(w, http.StatusBadRequest, "invalid id")
36
		return
37
	}
38
	b, err := getBook(a.DB, id)
39
	if err != nil {
40
		a.Log.Error("get book", "err", err)
41
		w.WriteHeader(http.StatusInternalServerError)
42
		return
43
	}
44
	if b == nil {
45
		web.WriteError(w, http.StatusNotFound, "not found")
46
		return
47
	}
48
	web.WriteJSON(w, http.StatusOK, b)
49
}