Skip to content

Commit

Permalink
Adds get by isbn route
Browse files Browse the repository at this point in the history
Note: gin router has some very serious limitations which mean that
it does not work with some typical rest route patterns. See e.g.
gin-gonic/gin#1681
  • Loading branch information
chrisk314 committed May 18, 2020
1 parent a642fc5 commit 92f2071
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 1 deletion.
1 change: 1 addition & 0 deletions backend/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ func main() {
books.GET("/:id", BooksGet)
books.PATCH("/:id", BooksUpdate)
books.DELETE("/:id", BooksDelete)
// books.GET("/isbn/:isbn", BooksGetByISBN) // gin router breaks for paths like this. See eg https://github.com/gin-gonic/gin/issues/1681. Consider switching framework
}
}

Expand Down
2 changes: 1 addition & 1 deletion backend/models/book.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ type Book struct {
Title string `json:"title" binding:"required"`
Authors string `json:"authors" binding:"required"`
AverageRating string `json:"average_rating"`
ISBN string `json:"isbn" binding:"required"`
ISBN string `json:"isbn" binding:"required" gorm:"index"`
ISBN13 string `json:"isbn_13"`
LanguageCode string `json:"language_code" binding:"required"`
NumPages int `json:"num_pages"`
Expand Down
12 changes: 12 additions & 0 deletions backend/routes.go
Original file line number Diff line number Diff line change
Expand Up @@ -77,3 +77,15 @@ func BooksDelete(c *gin.Context) {
db.Delete(&book)
c.JSON(http.StatusAccepted, gin.H{"data": true})
}

// BooksGetByISBN serves JSON response containing a single book by ISBN.
func BooksGetByISBN(c *gin.Context) {
db := c.MustGet("db").(*gorm.DB)
book := models.Book{}
if err := db.Where("isbn = ?", c.Param("isbn")).First(&book).Error; err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Record does not exist."})
return
}

c.JSON(http.StatusOK, gin.H{"data": book})
}

0 comments on commit 92f2071

Please sign in to comment.