initial commit for bookish-server and local environment
This commit is contained in:
@@ -0,0 +1,9 @@
|
||||
package bookish_server
|
||||
|
||||
// Book describes a book object that will be returned from the books API.
|
||||
type Book struct {
|
||||
Title string `json:"title"`
|
||||
Author *string `json:"author"`
|
||||
YearPublished *string `json:"year"`
|
||||
ISBN *string `json:"isbn"`
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"github.com/kelseyhightower/envconfig"
|
||||
)
|
||||
|
||||
type config struct {
|
||||
APIPort string
|
||||
LogLevel string
|
||||
DBHost string
|
||||
DBUser string
|
||||
DBPass string
|
||||
DBPort string
|
||||
BooksHost string
|
||||
}
|
||||
|
||||
func getConfig() (cfg config, err error) {
|
||||
err = envconfig.Process("", &cfg)
|
||||
return
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
"os/signal"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"github.com/davidlick/bookish/bookish-server/cmd/http"
|
||||
"github.com/davidlick/bookish/bookish-server/inventory"
|
||||
"github.com/davidlick/bookish/bookish-server/mysql"
|
||||
"github.com/davidlick/bookish/bookish-server/renter"
|
||||
"github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
var (
|
||||
cfg config
|
||||
err error
|
||||
logger = logrus.New()
|
||||
)
|
||||
|
||||
func init() {
|
||||
// Get configuration from the environment.
|
||||
cfg, err = getConfig()
|
||||
if err != nil {
|
||||
log.Fatal(err.Error())
|
||||
}
|
||||
|
||||
// Configure logger.
|
||||
logger.SetOutput(os.Stdout)
|
||||
logLevel, err := logrus.ParseLevel(cfg.LogLevel)
|
||||
if err != nil {
|
||||
log.Fatal(err.Error())
|
||||
}
|
||||
|
||||
logger.SetLevel(logLevel)
|
||||
logger.SetReportCaller(true)
|
||||
logger.SetFormatter(&logrus.JSONFormatter{})
|
||||
}
|
||||
|
||||
func main() {
|
||||
// Connect to application database and create store.
|
||||
appDSN := fmt.Sprintf("%s:%s@tcp(%s:%s)/bookish?parseTime=True&loc=Local",
|
||||
cfg.DBUser,
|
||||
cfg.DBPass,
|
||||
cfg.DBHost,
|
||||
cfg.DBPort,
|
||||
)
|
||||
appDB, err := mysql.NewStore(appDSN)
|
||||
if err != nil {
|
||||
log.Fatalf("could not connect to application database: %v", err.Error())
|
||||
}
|
||||
|
||||
// Build domain services.
|
||||
renterService := renter.NewService(appDB)
|
||||
inventoryService := inventory.NewService(appDB)
|
||||
|
||||
// Initialize server.
|
||||
server := http.Server{
|
||||
Port: cfg.APIPort,
|
||||
BooksHost: cfg.BooksHost,
|
||||
Logger: logger,
|
||||
Renter: renterService,
|
||||
Inventory: inventoryService,
|
||||
}
|
||||
|
||||
// Create channels to listen for OS signals.
|
||||
serverErrors := make(chan error, 1)
|
||||
osSignals := make(chan os.Signal, 1)
|
||||
signal.Notify(osSignals, os.Interrupt, syscall.SIGTERM)
|
||||
|
||||
// Start the server.
|
||||
go func() {
|
||||
serverErrors <- server.Run()
|
||||
}()
|
||||
|
||||
// Block until an error or interrupt/sigterm is received.
|
||||
select {
|
||||
case err := <-serverErrors:
|
||||
log.Fatalf("error starting server: %v", err.Error())
|
||||
case <-osSignals:
|
||||
log.Println("starting server shutdown...")
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
|
||||
err := server.Shutdown(ctx)
|
||||
if err != nil {
|
||||
log.Fatalf("error shutting down http server: %v", err.Error())
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
module github.com/davidlick/bookish/bookish-server
|
||||
|
||||
go 1.14
|
||||
|
||||
require (
|
||||
github.com/go-chi/chi v4.1.1+incompatible
|
||||
github.com/go-sql-driver/mysql v1.5.0
|
||||
github.com/golang/mock v1.4.3
|
||||
github.com/jmoiron/sqlx v1.2.0
|
||||
github.com/kelseyhightower/envconfig v1.4.0
|
||||
github.com/sirupsen/logrus v1.6.0
|
||||
github.com/stretchr/testify v1.5.1
|
||||
golang.org/x/net v0.0.0-20190603091049-60506f45cf65 // indirect
|
||||
golang.org/x/text v0.3.2 // indirect
|
||||
)
|
||||
@@ -0,0 +1,51 @@
|
||||
github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/go-chi/chi v4.1.1+incompatible h1:MmTgB0R8Bt/jccxp+t6S/1VGIKdJw5J74CK/c9tTfA4=
|
||||
github.com/go-chi/chi v4.1.1+incompatible/go.mod h1:eB3wogJHnLi3x/kFX2A+IbTBlXxmMeXJVKy9tTv1XzQ=
|
||||
github.com/go-sql-driver/mysql v1.4.0 h1:7LxgVwFb2hIQtMm87NdgAVfXjnt4OePseqT1tKx+opk=
|
||||
github.com/go-sql-driver/mysql v1.4.0/go.mod h1:zAC/RDZ24gD3HViQzih4MyKcchzm+sOG5ZlKdlhCg5w=
|
||||
github.com/go-sql-driver/mysql v1.5.0 h1:ozyZYNQW3x3HtqT1jira07DN2PArx2v7/mN66gGcHOs=
|
||||
github.com/go-sql-driver/mysql v1.5.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg=
|
||||
github.com/golang/mock v1.4.3 h1:GV+pQPG/EUUbkh47niozDcADz6go/dUwhVzdUQHIVRw=
|
||||
github.com/golang/mock v1.4.3/go.mod h1:UOMv5ysSaYNkG+OFQykRIcU/QvvxJf3p21QfJ2Bt3cw=
|
||||
github.com/jmoiron/sqlx v1.2.0 h1:41Ip0zITnmWNR/vHV+S4m+VoUivnWY5E4OJfLZjCJMA=
|
||||
github.com/jmoiron/sqlx v1.2.0/go.mod h1:1FEQNm3xlJgrMD+FBdI9+xvCksHtbpVBBw5dYhBSsks=
|
||||
github.com/kelseyhightower/envconfig v1.4.0 h1:Im6hONhd3pLkfDFsbRgu68RDNkGF1r3dvMUtDTo2cv8=
|
||||
github.com/kelseyhightower/envconfig v1.4.0/go.mod h1:cccZRl6mQpaq41TPp5QxidR+Sa3axMbJDNb//FQX6Gg=
|
||||
github.com/konsorten/go-windows-terminal-sequences v1.0.3 h1:CE8S1cTafDpPvMhIxNJKvHsGVBgn1xWYf1NbHQhywc8=
|
||||
github.com/konsorten/go-windows-terminal-sequences v1.0.3/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
|
||||
github.com/lib/pq v1.0.0 h1:X5PMW56eZitiTeO7tKzZxFCSpbFZJtkMMooicw2us9A=
|
||||
github.com/lib/pq v1.0.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo=
|
||||
github.com/mattn/go-sqlite3 v1.9.0 h1:pDRiWfl+++eC2FEFRy6jXmQlvp4Yh3z1MJKg4UeYM/4=
|
||||
github.com/mattn/go-sqlite3 v1.9.0/go.mod h1:FPy6KqzDD04eiIsT53CuJW3U88zkxoIYsOqkbpncsNc=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/sirupsen/logrus v1.6.0 h1:UBcNElsrwanuuMsnGSlYmtmgbb23qDR5dG+6X6Oo89I=
|
||||
github.com/sirupsen/logrus v1.6.0/go.mod h1:7uNnSEd1DgxDLC74fIahvMZmmYsHGZGEOFrfsX/uA88=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
|
||||
github.com/stretchr/testify v1.5.1 h1:nOGnQDM7FYENwehXlg/kFVnos3rEvtKTjRvOWSzb6H4=
|
||||
github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA=
|
||||
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||
golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
|
||||
golang.org/x/net v0.0.0-20190603091049-60506f45cf65 h1:+rhAzEzT3f4JtomfC371qB+0Ola2caSKcY69NUBZrRQ=
|
||||
golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks=
|
||||
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20190422165155-953cdadca894 h1:Cz4ceDQGXuKRnVBDTS23GTn/pU5OE2C0WrNTOYK1Uuc=
|
||||
golang.org/x/sys v0.0.0-20190422165155-953cdadca894/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
golang.org/x/text v0.3.2 h1:tW2bmiBqwgJj/UpqtC8EpXEZVYOwU0yG4iWbprSVAcs=
|
||||
golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=
|
||||
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||
golang.org/x/tools v0.0.0-20190425150028-36563e24a262 h1:qsl9y/CJx34tuA7QCPNp86JNJe4spst6Ff8MjvPUdPg=
|
||||
golang.org/x/tools v0.0.0-20190425150028-36563e24a262/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/yaml.v2 v2.2.2 h1:ZCJp+EgiOT7lHqUV2J862kp8Qj64Jo6az82+3Td9dZw=
|
||||
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||
rsc.io/quote/v3 v3.1.0/go.mod h1:yEA65RcK8LyAZtP9Kv3t0HmxON59tX3rD+tICJqUlj0=
|
||||
rsc.io/sampler v1.3.0/go.mod h1:T1hPZKmBbMNahiBKFy5HrXp6adAjACjK9JXDnKaTXpA=
|
||||
@@ -0,0 +1,6 @@
|
||||
package internal
|
||||
|
||||
type contextKey string
|
||||
|
||||
const CtxRenter contextKey = contextKey("ctx-renter")
|
||||
const CtxBookTitle contextKey = contextKey("ctx-book-title")
|
||||
@@ -0,0 +1,8 @@
|
||||
package inventory
|
||||
|
||||
import "errors"
|
||||
|
||||
var (
|
||||
ErrInvalidBook = errors.New("book not supported in library")
|
||||
ErrUnavailableBook = errors.New("book is not available at this library")
|
||||
)
|
||||
@@ -0,0 +1,58 @@
|
||||
package inventory
|
||||
|
||||
// Storage defines behavior for interacting with the inventory store.
|
||||
type Storage interface {
|
||||
IsBookAvailable(title string) (available bool, err error)
|
||||
RenterAlreadyCheckedOut(renterId int, title string) (checkedOut bool, err error)
|
||||
CheckoutBook(renterId int, title string) error
|
||||
ReturnBook(renterId int, title string) error
|
||||
}
|
||||
|
||||
type service struct {
|
||||
store Storage
|
||||
}
|
||||
|
||||
// Service defines behavior for interacting with the inventory service.
|
||||
type Service interface {
|
||||
IsBookAvailable(title string) (available bool, err error)
|
||||
CheckoutBook(renterId int, title string) error
|
||||
ReturnBook(renterId int, title string) error
|
||||
}
|
||||
|
||||
// NewService creates a new inventory service.
|
||||
func NewService(s Storage) *service {
|
||||
return &service{
|
||||
s,
|
||||
}
|
||||
}
|
||||
|
||||
// IsBookAvailable checks if a book is available to rent at this library.
|
||||
func (s *service) IsBookAvailable(title string) (available bool, err error) {
|
||||
return s.store.IsBookAvailable(title)
|
||||
}
|
||||
|
||||
// CheckoutBook checks a book out to a renter.
|
||||
func (s *service) CheckoutBook(renterId int, title string) error {
|
||||
available, err := s.IsBookAvailable(title)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if !available {
|
||||
return ErrUnavailableBook
|
||||
}
|
||||
|
||||
checkedOut, err := s.store.RenterAlreadyCheckedOut(renterId, title)
|
||||
// If there was an error or the book is checked out by the renter already we'll
|
||||
// say the book is unavailable.
|
||||
if err != nil || checkedOut {
|
||||
return ErrUnavailableBook
|
||||
}
|
||||
|
||||
return s.store.CheckoutBook(renterId, title)
|
||||
}
|
||||
|
||||
// ReturnBook returns a book for a renter.
|
||||
func (s *service) ReturnBook(renterId int, title string) error {
|
||||
return s.store.ReturnBook(renterId, title)
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
// Code generated by MockGen. DO NOT EDIT.
|
||||
// Source: inventory.go
|
||||
|
||||
// Package inventory is a generated GoMock package.
|
||||
package inventory
|
||||
|
||||
import (
|
||||
gomock "github.com/golang/mock/gomock"
|
||||
reflect "reflect"
|
||||
)
|
||||
|
||||
// MockStorage is a mock of Storage interface
|
||||
type MockStorage struct {
|
||||
ctrl *gomock.Controller
|
||||
recorder *MockStorageMockRecorder
|
||||
}
|
||||
|
||||
// MockStorageMockRecorder is the mock recorder for MockStorage
|
||||
type MockStorageMockRecorder struct {
|
||||
mock *MockStorage
|
||||
}
|
||||
|
||||
// NewMockStorage creates a new mock instance
|
||||
func NewMockStorage(ctrl *gomock.Controller) *MockStorage {
|
||||
mock := &MockStorage{ctrl: ctrl}
|
||||
mock.recorder = &MockStorageMockRecorder{mock}
|
||||
return mock
|
||||
}
|
||||
|
||||
// EXPECT returns an object that allows the caller to indicate expected use
|
||||
func (m *MockStorage) EXPECT() *MockStorageMockRecorder {
|
||||
return m.recorder
|
||||
}
|
||||
|
||||
// IsBookAvailable mocks base method
|
||||
func (m *MockStorage) IsBookAvailable(title string) (bool, error) {
|
||||
m.ctrl.T.Helper()
|
||||
ret := m.ctrl.Call(m, "IsBookAvailable", title)
|
||||
ret0, _ := ret[0].(bool)
|
||||
ret1, _ := ret[1].(error)
|
||||
return ret0, ret1
|
||||
}
|
||||
|
||||
// IsBookAvailable indicates an expected call of IsBookAvailable
|
||||
func (mr *MockStorageMockRecorder) IsBookAvailable(title interface{}) *gomock.Call {
|
||||
mr.mock.ctrl.T.Helper()
|
||||
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "IsBookAvailable", reflect.TypeOf((*MockStorage)(nil).IsBookAvailable), title)
|
||||
}
|
||||
|
||||
// RenterAlreadyCheckedOut mocks base method
|
||||
func (m *MockStorage) RenterAlreadyCheckedOut(renterId int, title string) (bool, error) {
|
||||
m.ctrl.T.Helper()
|
||||
ret := m.ctrl.Call(m, "RenterAlreadyCheckedOut", renterId, title)
|
||||
ret0, _ := ret[0].(bool)
|
||||
ret1, _ := ret[1].(error)
|
||||
return ret0, ret1
|
||||
}
|
||||
|
||||
// RenterAlreadyCheckedOut indicates an expected call of RenterAlreadyCheckedOut
|
||||
func (mr *MockStorageMockRecorder) RenterAlreadyCheckedOut(renterId, title interface{}) *gomock.Call {
|
||||
mr.mock.ctrl.T.Helper()
|
||||
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RenterAlreadyCheckedOut", reflect.TypeOf((*MockStorage)(nil).RenterAlreadyCheckedOut), renterId, title)
|
||||
}
|
||||
|
||||
// CheckoutBook mocks base method
|
||||
func (m *MockStorage) CheckoutBook(renterId int, title string) error {
|
||||
m.ctrl.T.Helper()
|
||||
ret := m.ctrl.Call(m, "CheckoutBook", renterId, title)
|
||||
ret0, _ := ret[0].(error)
|
||||
return ret0
|
||||
}
|
||||
|
||||
// CheckoutBook indicates an expected call of CheckoutBook
|
||||
func (mr *MockStorageMockRecorder) CheckoutBook(renterId, title interface{}) *gomock.Call {
|
||||
mr.mock.ctrl.T.Helper()
|
||||
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CheckoutBook", reflect.TypeOf((*MockStorage)(nil).CheckoutBook), renterId, title)
|
||||
}
|
||||
|
||||
// ReturnBook mocks base method
|
||||
func (m *MockStorage) ReturnBook(renterId int, title string) error {
|
||||
m.ctrl.T.Helper()
|
||||
ret := m.ctrl.Call(m, "ReturnBook", renterId, title)
|
||||
ret0, _ := ret[0].(error)
|
||||
return ret0
|
||||
}
|
||||
|
||||
// ReturnBook indicates an expected call of ReturnBook
|
||||
func (mr *MockStorageMockRecorder) ReturnBook(renterId, title interface{}) *gomock.Call {
|
||||
mr.mock.ctrl.T.Helper()
|
||||
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ReturnBook", reflect.TypeOf((*MockStorage)(nil).ReturnBook), renterId, title)
|
||||
}
|
||||
|
||||
// MockService is a mock of Service interface
|
||||
type MockService struct {
|
||||
ctrl *gomock.Controller
|
||||
recorder *MockServiceMockRecorder
|
||||
}
|
||||
|
||||
// MockServiceMockRecorder is the mock recorder for MockService
|
||||
type MockServiceMockRecorder struct {
|
||||
mock *MockService
|
||||
}
|
||||
|
||||
// NewMockService creates a new mock instance
|
||||
func NewMockService(ctrl *gomock.Controller) *MockService {
|
||||
mock := &MockService{ctrl: ctrl}
|
||||
mock.recorder = &MockServiceMockRecorder{mock}
|
||||
return mock
|
||||
}
|
||||
|
||||
// EXPECT returns an object that allows the caller to indicate expected use
|
||||
func (m *MockService) EXPECT() *MockServiceMockRecorder {
|
||||
return m.recorder
|
||||
}
|
||||
|
||||
// IsBookAvailable mocks base method
|
||||
func (m *MockService) IsBookAvailable(title string) (bool, error) {
|
||||
m.ctrl.T.Helper()
|
||||
ret := m.ctrl.Call(m, "IsBookAvailable", title)
|
||||
ret0, _ := ret[0].(bool)
|
||||
ret1, _ := ret[1].(error)
|
||||
return ret0, ret1
|
||||
}
|
||||
|
||||
// IsBookAvailable indicates an expected call of IsBookAvailable
|
||||
func (mr *MockServiceMockRecorder) IsBookAvailable(title interface{}) *gomock.Call {
|
||||
mr.mock.ctrl.T.Helper()
|
||||
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "IsBookAvailable", reflect.TypeOf((*MockService)(nil).IsBookAvailable), title)
|
||||
}
|
||||
|
||||
// CheckoutBook mocks base method
|
||||
func (m *MockService) CheckoutBook(renterId int, title string) error {
|
||||
m.ctrl.T.Helper()
|
||||
ret := m.ctrl.Call(m, "CheckoutBook", renterId, title)
|
||||
ret0, _ := ret[0].(error)
|
||||
return ret0
|
||||
}
|
||||
|
||||
// CheckoutBook indicates an expected call of CheckoutBook
|
||||
func (mr *MockServiceMockRecorder) CheckoutBook(renterId, title interface{}) *gomock.Call {
|
||||
mr.mock.ctrl.T.Helper()
|
||||
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CheckoutBook", reflect.TypeOf((*MockService)(nil).CheckoutBook), renterId, title)
|
||||
}
|
||||
|
||||
// ReturnBook mocks base method
|
||||
func (m *MockService) ReturnBook(renterId int, title string) error {
|
||||
m.ctrl.T.Helper()
|
||||
ret := m.ctrl.Call(m, "ReturnBook", renterId, title)
|
||||
ret0, _ := ret[0].(error)
|
||||
return ret0
|
||||
}
|
||||
|
||||
// ReturnBook indicates an expected call of ReturnBook
|
||||
func (mr *MockServiceMockRecorder) ReturnBook(renterId, title interface{}) *gomock.Call {
|
||||
mr.mock.ctrl.T.Helper()
|
||||
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ReturnBook", reflect.TypeOf((*MockService)(nil).ReturnBook), renterId, title)
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
package inventory
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"github.com/golang/mock/gomock"
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestInventory_IsBookAvailable(t *testing.T) {
|
||||
testCases := []struct {
|
||||
TestName string
|
||||
Title string
|
||||
RenterId int
|
||||
Available bool
|
||||
Error error
|
||||
}{
|
||||
{
|
||||
TestName: "success-available",
|
||||
Title: "Book #1",
|
||||
Available: true,
|
||||
},
|
||||
{
|
||||
TestName: "success-unavailable",
|
||||
Title: "Book #2",
|
||||
Available: false,
|
||||
},
|
||||
{
|
||||
TestName: "failure",
|
||||
Title: "Book #3",
|
||||
Error: errors.New("test error"),
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range testCases {
|
||||
t.Run(tc.TestName, func(t *testing.T) {
|
||||
ctrl := gomock.NewController(t)
|
||||
defer ctrl.Finish()
|
||||
|
||||
mockStorage := NewMockStorage(ctrl)
|
||||
mockStorage.EXPECT().IsBookAvailable(tc.Title).Return(tc.Available, tc.Error)
|
||||
|
||||
service := NewService(mockStorage)
|
||||
available, err := service.IsBookAvailable(tc.Title)
|
||||
|
||||
assert.Equal(t, tc.Available, available)
|
||||
assert.Equal(t, tc.Error, err)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestInventory_CheckoutBook(t *testing.T) {
|
||||
testCases := []struct {
|
||||
TestName string
|
||||
RenterId int
|
||||
Title string
|
||||
Available bool
|
||||
AvailableError error
|
||||
CheckedOut bool
|
||||
CheckedOutError error
|
||||
Error error
|
||||
}{
|
||||
{
|
||||
TestName: "success",
|
||||
RenterId: 1,
|
||||
Title: "Book #1",
|
||||
Available: true,
|
||||
},
|
||||
{
|
||||
TestName: "unavailable",
|
||||
RenterId: 2,
|
||||
Title: "Book #2",
|
||||
Available: false,
|
||||
Error: ErrUnavailableBook,
|
||||
},
|
||||
{
|
||||
TestName: "availability_error",
|
||||
RenterId: 3,
|
||||
Title: "Book #3",
|
||||
AvailableError: errors.New("test error"),
|
||||
Error: errors.New("test error"),
|
||||
},
|
||||
{
|
||||
TestName: "checked-out",
|
||||
RenterId: 4,
|
||||
Title: "Book #4",
|
||||
Available: true,
|
||||
CheckedOut: true,
|
||||
Error: ErrUnavailableBook,
|
||||
},
|
||||
{
|
||||
TestName: "failure",
|
||||
RenterId: 4,
|
||||
Title: "Book #4",
|
||||
Available: true,
|
||||
Error: errors.New("test error"),
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range testCases {
|
||||
t.Run(tc.TestName, func(t *testing.T) {
|
||||
ctrl := gomock.NewController(t)
|
||||
defer ctrl.Finish()
|
||||
|
||||
mockStorage := NewMockStorage(ctrl)
|
||||
mockStorage.EXPECT().IsBookAvailable(tc.Title).Return(tc.Available, tc.AvailableError)
|
||||
if tc.Available && tc.AvailableError == nil {
|
||||
mockStorage.EXPECT().RenterAlreadyCheckedOut(tc.RenterId, tc.Title).Return(tc.CheckedOut, tc.CheckedOutError)
|
||||
if !tc.CheckedOut && tc.CheckedOutError == nil {
|
||||
mockStorage.EXPECT().CheckoutBook(tc.RenterId, tc.Title).Return(tc.Error)
|
||||
}
|
||||
}
|
||||
|
||||
service := NewService(mockStorage)
|
||||
err := service.CheckoutBook(tc.RenterId, tc.Title)
|
||||
|
||||
assert.Equal(t, tc.Error, err)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestInventory_ReturnBook(t *testing.T) {
|
||||
testCases := []struct {
|
||||
TestName string
|
||||
RenterId int
|
||||
Title string
|
||||
Error error
|
||||
}{
|
||||
{
|
||||
TestName: "success",
|
||||
RenterId: 1,
|
||||
Title: "Book #1",
|
||||
},
|
||||
{
|
||||
TestName: "failure",
|
||||
RenterId: 2,
|
||||
Title: "Book #2",
|
||||
Error: errors.New("test error"),
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range testCases {
|
||||
t.Run(tc.TestName, func(t *testing.T) {
|
||||
ctrl := gomock.NewController(t)
|
||||
defer ctrl.Finish()
|
||||
|
||||
mockStorage := NewMockStorage(ctrl)
|
||||
mockStorage.EXPECT().ReturnBook(tc.RenterId, tc.Title).Return(tc.Error)
|
||||
|
||||
service := NewService(mockStorage)
|
||||
err := service.ReturnBook(tc.RenterId, tc.Title)
|
||||
|
||||
assert.Equal(t, tc.Error, err)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package mysql
|
||||
|
||||
import (
|
||||
"errors"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrNotFound = errors.New("no renter found")
|
||||
ErrAlreadyExists = errors.New("the provided value already exists")
|
||||
)
|
||||
@@ -0,0 +1,111 @@
|
||||
package mysql
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"errors"
|
||||
"time"
|
||||
)
|
||||
|
||||
// IsBookAvailable queries the database for available books.
|
||||
func (s *store) IsBookAvailable(title string) (available bool, err error) {
|
||||
q := `
|
||||
SELECT
|
||||
*
|
||||
FROM
|
||||
rentals
|
||||
WHERE
|
||||
book_title = ?
|
||||
AND return_date IS NULL;
|
||||
`
|
||||
|
||||
var rr []struct {
|
||||
ID int `db:"id"`
|
||||
RenterID int `db:"renter_id"`
|
||||
RentalDate time.Time `db:"rental_date"`
|
||||
ReturnDate sql.NullTime `db:"return_date"`
|
||||
BookTitle string `db:"book_title"`
|
||||
}
|
||||
|
||||
err = s.Select(&rr, q, title)
|
||||
if err != nil {
|
||||
// If no records are returned then the book is available for rent.
|
||||
if errors.Is(sql.ErrNoRows, err) {
|
||||
return true, nil
|
||||
}
|
||||
|
||||
return false, err
|
||||
}
|
||||
|
||||
// If 5 books are rented out this book is not available.
|
||||
if len(rr) > 4 {
|
||||
return false, nil
|
||||
}
|
||||
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// RenterAlreadyCheckedOut queries the database for the given renterId and title. If a record is returned checkedOut will be true.
|
||||
func (s *store) RenterAlreadyCheckedOut(renterId int, title string) (checkedOut bool, err error) {
|
||||
q := `
|
||||
SELECT
|
||||
*
|
||||
FROM
|
||||
rentals
|
||||
WHERE
|
||||
renter_id = ?
|
||||
AND book_title = ?
|
||||
AND return_date IS NULL;
|
||||
`
|
||||
|
||||
var rr []struct {
|
||||
ID int `db:"id"`
|
||||
RenterID int `db:"renter_id"`
|
||||
RentalDate time.Time `db:"rental_date"`
|
||||
ReturnDate sql.NullTime `db:"return_date"`
|
||||
BookTitle string `db:"book_title"`
|
||||
}
|
||||
|
||||
err = s.Select(&rr, q, renterId, title)
|
||||
if err != nil {
|
||||
if errors.Is(sql.ErrNoRows, err) {
|
||||
return false, nil
|
||||
}
|
||||
|
||||
return false, err
|
||||
}
|
||||
|
||||
if len(rr) == 0 {
|
||||
return false, nil
|
||||
}
|
||||
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// CheckoutBook inserts a record indicating the book is checked out to the renter.
|
||||
func (s *store) CheckoutBook(renterId int, title string) error {
|
||||
q := `
|
||||
INSERT INTO
|
||||
rentals (renter_id, rental_date, book_title)
|
||||
VALUES
|
||||
(?, ?, ?);
|
||||
`
|
||||
|
||||
_, err := s.Exec(q, renterId, time.Now(), title)
|
||||
return err
|
||||
}
|
||||
|
||||
// ReturnBook sets the return_date field to now indicating the book has been returned.
|
||||
func (s *store) ReturnBook(renterId int, title string) error {
|
||||
q := `
|
||||
UPDATE
|
||||
rentals
|
||||
SET
|
||||
return_date = ?
|
||||
WHERE
|
||||
renter_id = ?
|
||||
AND book_title = ?;
|
||||
`
|
||||
|
||||
_, err := s.Exec(q, time.Now(), renterId, title)
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package mysql
|
||||
|
||||
import (
|
||||
"github.com/jmoiron/sqlx"
|
||||
)
|
||||
|
||||
// store holds a connection to the application database.
|
||||
type store struct {
|
||||
*sqlx.DB
|
||||
}
|
||||
|
||||
// NewStore creates a new connection to the database and returns a store containing the connection.
|
||||
func NewStore(dsn string) (s *store, err error) {
|
||||
db, err := sqlx.Open("mysql", dsn)
|
||||
if err != nil {
|
||||
return s, err
|
||||
}
|
||||
|
||||
return &store{db}, nil
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
package mysql
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"errors"
|
||||
|
||||
bookish "github.com/davidlick/bookish/bookish-server"
|
||||
"github.com/go-sql-driver/mysql"
|
||||
)
|
||||
|
||||
// ListAll returns all renter records.
|
||||
func (s *store) ListAll() (rr []bookish.Renter, err error) {
|
||||
q := `
|
||||
SELECT
|
||||
*
|
||||
FROM
|
||||
renters
|
||||
`
|
||||
|
||||
err = s.Select(&rr, q)
|
||||
if err != nil && errors.Is(sql.ErrNoRows, err) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// FetchDetails queries the database for a specific renter.
|
||||
func (s *store) FetchDetails(id int) (r bookish.Renter, err error) {
|
||||
q := `
|
||||
SELECT
|
||||
*
|
||||
FROM
|
||||
renters
|
||||
WHERE
|
||||
id = ?
|
||||
`
|
||||
|
||||
err = s.Get(&r, q, id)
|
||||
if err != nil && errors.Is(sql.ErrNoRows, err) {
|
||||
return bookish.Renter{}, ErrNotFound
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// New inserts a record for a new renter. If that renter already exists it returns an ErrAlreadyExists.
|
||||
func (s *store) New(name string, address string, email string, phoneNumber string) (id int, err error) {
|
||||
q := `
|
||||
INSERT INTO
|
||||
renters (name, address, email, phone_number)
|
||||
VALUES
|
||||
(?, ?, ?, ?)
|
||||
`
|
||||
|
||||
result, err := s.Exec(q, name, address, email, phoneNumber)
|
||||
if err != nil {
|
||||
if _, ok := err.(*mysql.MySQLError); ok {
|
||||
return 0, ErrAlreadyExists
|
||||
}
|
||||
}
|
||||
|
||||
lastId, err := result.LastInsertId()
|
||||
if err != nil {
|
||||
return id, err
|
||||
}
|
||||
return int(lastId), nil
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package bookish_server
|
||||
|
||||
// Renter is an entity in the Bookish API wish rents books.
|
||||
type Renter struct {
|
||||
ID int `db:"id" json:"id"`
|
||||
Name string `db:"name" json:"name"`
|
||||
Address string `db:"address" json:"address"`
|
||||
Email string `db:"email" json:"email"`
|
||||
PhoneNumber string `db:"phone_number" json:"phoneNumber"`
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package renter
|
||||
|
||||
import (
|
||||
"errors"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrNotFound = errors.New("no renter found")
|
||||
ErrInvalidRenter = errors.New("invalid renter provided")
|
||||
)
|
||||
@@ -0,0 +1,45 @@
|
||||
package renter
|
||||
|
||||
import (
|
||||
bookish "github.com/davidlick/bookish/bookish-server"
|
||||
)
|
||||
|
||||
// Storage defines behavior for interacting with the renter store.
|
||||
type Storage interface {
|
||||
ListAll() (rr []bookish.Renter, err error)
|
||||
FetchDetails(id int) (r bookish.Renter, err error)
|
||||
New(name string, address string, email string, phoneNumber string) (id int, err error)
|
||||
}
|
||||
|
||||
type service struct {
|
||||
store Storage
|
||||
}
|
||||
|
||||
// Service defines behavior for interacting with the renter service.
|
||||
type Service interface {
|
||||
ListRenters() (rr []bookish.Renter, err error)
|
||||
FetchRenter(id int) (r bookish.Renter, err error)
|
||||
RegisterRenter(fullName string, address string, email string, phoneNumber string) (id int, err error)
|
||||
}
|
||||
|
||||
// NewService creates a new renter service.
|
||||
func NewService(s Storage) *service {
|
||||
return &service{
|
||||
s,
|
||||
}
|
||||
}
|
||||
|
||||
// ListRenters returns all renters from the renter store.
|
||||
func (s *service) ListRenters() (rr []bookish.Renter, err error) {
|
||||
return s.store.ListAll()
|
||||
}
|
||||
|
||||
// FetchRenter returns a specific renter from the renter store.
|
||||
func (s *service) FetchRenter(id int) (r bookish.Renter, err error) {
|
||||
return s.store.FetchDetails(id)
|
||||
}
|
||||
|
||||
// RegisterRenter registers a new renter in the renter store.
|
||||
func (s *service) RegisterRenter(fullName string, address string, email string, phoneNumber string) (id int, err error) {
|
||||
return s.store.New(fullName, address, email, phoneNumber)
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
// Code generated by MockGen. DO NOT EDIT.
|
||||
// Source: ./renter.go
|
||||
|
||||
// Package renter is a generated GoMock package.
|
||||
package renter
|
||||
|
||||
import (
|
||||
bookish_server "github.com/davidlick/bookish/bookish-server"
|
||||
gomock "github.com/golang/mock/gomock"
|
||||
reflect "reflect"
|
||||
)
|
||||
|
||||
// MockStorage is a mock of Storage interface
|
||||
type MockStorage struct {
|
||||
ctrl *gomock.Controller
|
||||
recorder *MockStorageMockRecorder
|
||||
}
|
||||
|
||||
// MockStorageMockRecorder is the mock recorder for MockStorage
|
||||
type MockStorageMockRecorder struct {
|
||||
mock *MockStorage
|
||||
}
|
||||
|
||||
// NewMockStorage creates a new mock instance
|
||||
func NewMockStorage(ctrl *gomock.Controller) *MockStorage {
|
||||
mock := &MockStorage{ctrl: ctrl}
|
||||
mock.recorder = &MockStorageMockRecorder{mock}
|
||||
return mock
|
||||
}
|
||||
|
||||
// EXPECT returns an object that allows the caller to indicate expected use
|
||||
func (m *MockStorage) EXPECT() *MockStorageMockRecorder {
|
||||
return m.recorder
|
||||
}
|
||||
|
||||
// ListAll mocks base method
|
||||
func (m *MockStorage) ListAll() ([]bookish_server.Renter, error) {
|
||||
m.ctrl.T.Helper()
|
||||
ret := m.ctrl.Call(m, "ListAll")
|
||||
ret0, _ := ret[0].([]bookish_server.Renter)
|
||||
ret1, _ := ret[1].(error)
|
||||
return ret0, ret1
|
||||
}
|
||||
|
||||
// ListAll indicates an expected call of ListAll
|
||||
func (mr *MockStorageMockRecorder) ListAll() *gomock.Call {
|
||||
mr.mock.ctrl.T.Helper()
|
||||
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListAll", reflect.TypeOf((*MockStorage)(nil).ListAll))
|
||||
}
|
||||
|
||||
// FetchDetails mocks base method
|
||||
func (m *MockStorage) FetchDetails(id int) (bookish_server.Renter, error) {
|
||||
m.ctrl.T.Helper()
|
||||
ret := m.ctrl.Call(m, "FetchDetails", id)
|
||||
ret0, _ := ret[0].(bookish_server.Renter)
|
||||
ret1, _ := ret[1].(error)
|
||||
return ret0, ret1
|
||||
}
|
||||
|
||||
// FetchDetails indicates an expected call of FetchDetails
|
||||
func (mr *MockStorageMockRecorder) FetchDetails(id interface{}) *gomock.Call {
|
||||
mr.mock.ctrl.T.Helper()
|
||||
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "FetchDetails", reflect.TypeOf((*MockStorage)(nil).FetchDetails), id)
|
||||
}
|
||||
|
||||
// New mocks base method
|
||||
func (m *MockStorage) New(name, address, email, phoneNumber string) (int, error) {
|
||||
m.ctrl.T.Helper()
|
||||
ret := m.ctrl.Call(m, "New", name, address, email, phoneNumber)
|
||||
ret0, _ := ret[0].(int)
|
||||
ret1, _ := ret[1].(error)
|
||||
return ret0, ret1
|
||||
}
|
||||
|
||||
// New indicates an expected call of New
|
||||
func (mr *MockStorageMockRecorder) New(name, address, email, phoneNumber interface{}) *gomock.Call {
|
||||
mr.mock.ctrl.T.Helper()
|
||||
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "New", reflect.TypeOf((*MockStorage)(nil).New), name, address, email, phoneNumber)
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
package renter
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
bookish "github.com/davidlick/bookish/bookish-server"
|
||||
"github.com/golang/mock/gomock"
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestRenter_ListRenters(t *testing.T) {
|
||||
testCases := []struct {
|
||||
TestName string
|
||||
Renters []bookish.Renter
|
||||
Error error
|
||||
}{
|
||||
{
|
||||
TestName: "success",
|
||||
Renters: []bookish.Renter{
|
||||
{
|
||||
Name: "John Doe",
|
||||
Address: "123 Main Way",
|
||||
Email: "john@doe.com",
|
||||
PhoneNumber: "5551234567",
|
||||
},
|
||||
{
|
||||
Name: "Jack Doe",
|
||||
Address: "123 Elm Street",
|
||||
Email: "jack@doe.com",
|
||||
PhoneNumber: "1112223333",
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
TestName: "error",
|
||||
Error: errors.New("test error"),
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range testCases {
|
||||
t.Run(tc.TestName, func(t *testing.T) {
|
||||
ctrl := gomock.NewController(t)
|
||||
defer ctrl.Finish()
|
||||
|
||||
mockStorage := NewMockStorage(ctrl)
|
||||
mockStorage.EXPECT().ListAll().Return(tc.Renters, tc.Error)
|
||||
|
||||
service := NewService(mockStorage)
|
||||
renters, err := service.ListRenters()
|
||||
|
||||
assert.Equal(t, tc.Renters, renters)
|
||||
assert.Equal(t, tc.Error, err)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestRenter_FetchRenter(t *testing.T) {
|
||||
testCases := []struct {
|
||||
TestName string
|
||||
ID int
|
||||
Renter bookish.Renter
|
||||
Error error
|
||||
}{
|
||||
{
|
||||
TestName: "success",
|
||||
ID: 1,
|
||||
Renter: bookish.Renter{
|
||||
Name: "John Smith",
|
||||
Address: "123 Main Way",
|
||||
Email: "john@smith.com",
|
||||
PhoneNumber: "5551234567",
|
||||
},
|
||||
},
|
||||
{
|
||||
TestName: "error",
|
||||
ID: 1,
|
||||
Error: errors.New("test error"),
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range testCases {
|
||||
t.Run(tc.TestName, func(t *testing.T) {
|
||||
ctrl := gomock.NewController(t)
|
||||
defer ctrl.Finish()
|
||||
|
||||
mockStorage := NewMockStorage(ctrl)
|
||||
mockStorage.EXPECT().FetchDetails(tc.ID).Return(tc.Renter, tc.Error)
|
||||
|
||||
service := NewService(mockStorage)
|
||||
renter, err := service.FetchRenter(tc.ID)
|
||||
|
||||
assert.Equal(t, tc.Renter, renter)
|
||||
assert.Equal(t, tc.Error, err)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestRenter_RegisterRenter(t *testing.T) {
|
||||
testCases := []struct {
|
||||
TestName string
|
||||
Name string
|
||||
Address string
|
||||
Email string
|
||||
PhoneNumber string
|
||||
ReturnID int
|
||||
Error error
|
||||
}{
|
||||
{
|
||||
TestName: "success",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range testCases {
|
||||
t.Run(tc.TestName, func(t *testing.T) {
|
||||
ctrl := gomock.NewController(t)
|
||||
defer ctrl.Finish()
|
||||
|
||||
mockStorage := NewMockStorage(ctrl)
|
||||
mockStorage.EXPECT().New(tc.Name, tc.Address, tc.Email, tc.PhoneNumber).Return(tc.ReturnID, tc.Error)
|
||||
|
||||
service := NewService(mockStorage)
|
||||
id, err := service.RegisterRenter(tc.Name, tc.Address, tc.Email, tc.PhoneNumber)
|
||||
|
||||
assert.Equal(t, tc.ReturnID, id)
|
||||
assert.Equal(t, tc.Error, err)
|
||||
})
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user