initial commit for bookish-server and local environment
This commit is contained in:
@@ -0,0 +1,117 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
bookish "github.com/davidlick/bookish/bookish-server"
|
||||
"github.com/davidlick/bookish/bookish-server/inventory"
|
||||
"github.com/davidlick/bookish/bookish-server/renter"
|
||||
"github.com/go-chi/chi"
|
||||
"github.com/go-chi/chi/middleware"
|
||||
"github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
// Server holds dependencies of the API.
|
||||
type Server struct {
|
||||
Port string
|
||||
BooksHost string
|
||||
Logger *logrus.Logger
|
||||
Renter renter.Service
|
||||
Inventory inventory.Service
|
||||
// LibraryMap holds a map of values that are returned by the books API. This is used to check
|
||||
// if a book exists in the library.
|
||||
LibraryMap struct {
|
||||
UpdatedTime time.Time
|
||||
Map map[string]bookish.Book
|
||||
}
|
||||
server *http.Server
|
||||
}
|
||||
|
||||
// Run configures and starts the server.
|
||||
func (s *Server) Run() error {
|
||||
s.server = &http.Server{
|
||||
Addr: ":" + s.Port,
|
||||
ReadTimeout: 30 * time.Second,
|
||||
WriteTimeout: 30 * time.Second,
|
||||
Handler: s.BuildRoutes(),
|
||||
}
|
||||
|
||||
s.Logger.Info("server launched on port: " + s.Port)
|
||||
return s.server.ListenAndServe()
|
||||
}
|
||||
|
||||
// Shutdown attempts to gracefully shutdown the server.
|
||||
func (s *Server) Shutdown(ctx context.Context) error {
|
||||
return s.server.Shutdown(ctx)
|
||||
}
|
||||
|
||||
// UpdateMap will query the books API if 1 hour has passed since the data was last refreshed.
|
||||
func (s *Server) UpdateMap() error {
|
||||
// If it has not been at least an hour since the last refresh we do not need to refresh.
|
||||
if !time.Now().After(s.LibraryMap.UpdatedTime.Add(1 * time.Hour)) {
|
||||
return nil
|
||||
}
|
||||
|
||||
resp, err := http.Get(fmt.Sprintf("%s/api/v1/books", s.BooksHost))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
respBytes, err := ioutil.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var books []bookish.Book
|
||||
err = json.Unmarshal(respBytes, &books)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Empty the existing map.
|
||||
s.LibraryMap.Map = map[string]bookish.Book{}
|
||||
|
||||
for _, book := range books {
|
||||
s.LibraryMap.Map[book.Title] = book
|
||||
}
|
||||
|
||||
s.LibraryMap.UpdatedTime = time.Now()
|
||||
return nil
|
||||
}
|
||||
|
||||
// BuildRoutes builds the API endpoints and connects their handlers.
|
||||
func (s *Server) BuildRoutes() http.Handler {
|
||||
r := chi.NewRouter()
|
||||
|
||||
r.Use(middleware.RequestID)
|
||||
r.Use(middleware.RealIP)
|
||||
r.Use(middleware.Logger)
|
||||
r.Use(middleware.Recoverer)
|
||||
|
||||
r.Group(func(r chi.Router) {
|
||||
r.Route("/api", func(r chi.Router) {
|
||||
r.Route("/v1", func(r chi.Router) {
|
||||
r.Route("/renters", func(r chi.Router) {
|
||||
r.Post("/", s.registerRenter)
|
||||
r.Get("/", s.listRenters)
|
||||
r.Route("/{renterId}", func(r chi.Router) {
|
||||
r.Use(s.renterCtx)
|
||||
r.Get("/", s.fetchRenter)
|
||||
r.Route("/books", func(r chi.Router) {
|
||||
r.Use(s.bookInLibrary)
|
||||
r.Post("/checkout", s.checkoutBook)
|
||||
r.Post("/return", s.returnBook)
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
return r
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
|
||||
bookish "github.com/davidlick/bookish/bookish-server"
|
||||
"github.com/davidlick/bookish/bookish-server/internal"
|
||||
"github.com/davidlick/bookish/bookish-server/inventory"
|
||||
)
|
||||
|
||||
// checkoutBook is used to checkout a book for a renter.
|
||||
func (s *Server) checkoutBook(w http.ResponseWriter, r *http.Request) {
|
||||
ctx := r.Context()
|
||||
renter, ok := ctx.Value(internal.CtxRenter).(bookish.Renter)
|
||||
if !ok {
|
||||
http.Error(w, http.StatusText(http.StatusUnprocessableEntity), http.StatusUnprocessableEntity)
|
||||
return
|
||||
}
|
||||
|
||||
bookTitle, ok := ctx.Value(internal.CtxBookTitle).(string)
|
||||
if !ok {
|
||||
http.Error(w, http.StatusText(http.StatusUnprocessableEntity), http.StatusUnprocessableEntity)
|
||||
return
|
||||
}
|
||||
|
||||
err := s.Inventory.CheckoutBook(renter.ID, bookTitle)
|
||||
if err != nil {
|
||||
if errors.Is(inventory.ErrUnavailableBook, err) {
|
||||
http.Error(w, err.Error(), http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
|
||||
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// returnBook returns a book for a renter.
|
||||
func (s *Server) returnBook(w http.ResponseWriter, r *http.Request) {
|
||||
ctx := r.Context()
|
||||
renter, ok := ctx.Value(internal.CtxRenter).(bookish.Renter)
|
||||
if !ok {
|
||||
http.Error(w, http.StatusText(http.StatusUnprocessableEntity), http.StatusUnprocessableEntity)
|
||||
return
|
||||
}
|
||||
|
||||
bookTitle, ok := ctx.Value(internal.CtxBookTitle).(string)
|
||||
if !ok {
|
||||
http.Error(w, http.StatusText(http.StatusUnprocessableEntity), http.StatusUnprocessableEntity)
|
||||
return
|
||||
}
|
||||
|
||||
err := s.Inventory.ReturnBook(renter.ID, bookTitle)
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"github.com/davidlick/bookish/bookish-server/internal"
|
||||
"github.com/davidlick/bookish/bookish-server/mysql"
|
||||
"github.com/go-chi/chi"
|
||||
)
|
||||
|
||||
// renterCtx is a convenience handler to fetch the renter with the provided renterId URLParam.
|
||||
func (s *Server) renterCtx(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
ctx := r.Context()
|
||||
id := chi.URLParam(r, "renterId")
|
||||
|
||||
renterId, err := strconv.Atoi(id)
|
||||
if err != nil {
|
||||
http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
renter, err := s.Renter.FetchRenter(renterId)
|
||||
if err != nil && errors.Is(mysql.ErrNotFound, err) {
|
||||
http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
|
||||
return
|
||||
} else if err != nil {
|
||||
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
ctx = context.WithValue(ctx, internal.CtxRenter, renter)
|
||||
next.ServeHTTP(w, r.WithContext(ctx))
|
||||
})
|
||||
}
|
||||
|
||||
// bookInLibrary is a convenience handler that queries the books API for a map of books available
|
||||
// at the library.
|
||||
func (s *Server) bookInLibrary(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
ctx := r.Context()
|
||||
s.UpdateMap()
|
||||
|
||||
reqBytes, err := ioutil.ReadAll(r.Body)
|
||||
if err != nil {
|
||||
http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
var req struct {
|
||||
Title string `json:"title"`
|
||||
}
|
||||
|
||||
err = json.Unmarshal(reqBytes, &req)
|
||||
if err != nil {
|
||||
http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
if _, found := s.LibraryMap.Map[req.Title]; !found {
|
||||
http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
ctx = context.WithValue(ctx, internal.CtxBookTitle, req.Title)
|
||||
next.ServeHTTP(w, r.WithContext(ctx))
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
|
||||
bookish "github.com/davidlick/bookish/bookish-server"
|
||||
"github.com/davidlick/bookish/bookish-server/internal"
|
||||
)
|
||||
|
||||
// registerRenter creates a record of a new renter.
|
||||
func (s *Server) registerRenter(w http.ResponseWriter, r *http.Request) {
|
||||
reqBytes, err := ioutil.ReadAll(r.Body)
|
||||
if err != nil {
|
||||
http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
var renter bookish.Renter
|
||||
err = json.Unmarshal(reqBytes, &renter)
|
||||
if err != nil {
|
||||
http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
id, err := s.Renter.RegisterRenter(renter.Name, renter.Address, renter.Email, renter.PhoneNumber)
|
||||
if err != nil {
|
||||
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
resp := struct {
|
||||
ID int `json:"renterId"`
|
||||
}{ID: id}
|
||||
|
||||
json.NewEncoder(w).Encode(resp)
|
||||
}
|
||||
|
||||
// listRenters lists all renters registered in the API.
|
||||
func (s *Server) listRenters(w http.ResponseWriter, r *http.Request) {
|
||||
rr, err := s.Renter.ListRenters()
|
||||
if err != nil {
|
||||
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
json.NewEncoder(w).Encode(rr)
|
||||
}
|
||||
|
||||
// fetchRenter fetches a specific renter's details.
|
||||
func (s *Server) fetchRenter(w http.ResponseWriter, r *http.Request) {
|
||||
ctx := r.Context()
|
||||
renter, ok := ctx.Value(internal.CtxRenter).(bookish.Renter)
|
||||
if !ok {
|
||||
http.Error(w, http.StatusText(http.StatusUnprocessableEntity), http.StatusUnprocessableEntity)
|
||||
return
|
||||
}
|
||||
|
||||
json.NewEncoder(w).Encode(renter)
|
||||
}
|
||||
Reference in New Issue
Block a user