Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cohort 1.5 exercise #6

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
193 changes: 154 additions & 39 deletions controllers/library.go
Original file line number Diff line number Diff line change
@@ -1,84 +1,199 @@
package controllers

import (
"context"
"acme-books/models"
"encoding/json"
"fmt"
"github.com/go-martini/martini"
"log"
"net/http"
"strconv"

"cloud.google.com/go/datastore"
"github.com/go-martini/martini"
"google.golang.org/api/iterator"

"acme-books/models"
)

type LibraryController struct{}

func (lc LibraryController) GetByKey(params martini.Params, w http.ResponseWriter) {
ctx := context.Background()
client, _ := datastore.NewClient(ctx, "acme-books")
id, err := strconv.Atoi(params["id"])

if err != nil {
handleError("Invalid id", http.StatusBadRequest, w)
return
}

book, err := models.GetBookById(int64(id))

if err != nil {
handleError("Invalid id", http.StatusBadRequest, w)
return
}

showBookInfo(book, w)
}

func (lc LibraryController) ListAll(r *http.Request, w http.ResponseWriter) {
books, err := models.GetBooks(getFilters(r), "Id")

if err != nil {
handleError("Internal error", http.StatusInternalServerError, w)
return
}

defer client.Close()
showAllBooksInfo(books, w)
}

func (lc LibraryController) Borrow(params martini.Params, w http.ResponseWriter) {
id, err := strconv.Atoi(params["id"])

if err != nil {
fmt.Println(err)
w.WriteHeader(http.StatusBadRequest)
handleError("Invalid id", http.StatusBadRequest, w)
return
}

book, err := models.GetBookById(int64(id))

if err != nil {
handleError("Invalid id", http.StatusBadRequest, w)
return
}

var book models.Book
key := datastore.IDKey("Book", int64(id), nil)
if book.Borrowed {
handleError("Already borrowed", http.StatusBadRequest, w)
return
}

err = client.Get(ctx, key, &book)
if err := book.Borrow(); err != nil {
handleError("Internal error", http.StatusInternalServerError, w)
return
}

showBookInfo(book, w)
}

func (lc LibraryController) Return(params martini.Params, w http.ResponseWriter) {
id, err := strconv.Atoi(params["id"])

if err != nil {
fmt.Println(err)
w.WriteHeader(http.StatusInternalServerError)
handleError("Invalid id", http.StatusBadRequest, w)
return
}

jsonStr, err := json.MarshalIndent(book, "", " ")
book, err := models.GetBookById(int64(id))

if err != nil {
fmt.Println(err)
w.WriteHeader(http.StatusInternalServerError)
handleError("Invalid id", http.StatusBadRequest, w)
return
}

w.WriteHeader(http.StatusOK)
w.Write(jsonStr)
if !book.Borrowed {
handleError("Not borrowed", http.StatusBadRequest, w)
return
}

if err := book.Return(); err != nil {
handleError("Internal error", http.StatusInternalServerError, w)
return
}

showBookInfo(book, w)
}

func (lc LibraryController) ListAll(r *http.Request, w http.ResponseWriter) {
ctx := context.Background()
client, _ := datastore.NewClient(ctx, "acme-books")
func (lc LibraryController) Add(r *http.Request, w http.ResponseWriter) {
r.ParseForm()

defer client.Close()
id, err := strconv.ParseInt(r.Form.Get("id"), 10, 64)
if err != nil {
handleError("Invalid/missing id", http.StatusBadRequest, w)
return
}
if id == 0 {
handleError("Missing id", http.StatusBadRequest, w)
return
}

var output []models.Book
book, err := models.GetBookById(id)

it := client.Run(ctx, datastore.NewQuery("Book"))
for {
var b models.Book
_, err := it.Next(&b)
if err == iterator.Done {
fmt.Println(err)
break
}
output = append(output, b)
if err != nil && book.Id != 0 {
handleError("Internal error", http.StatusInternalServerError, w)
return
}
if book.Id != 0 {
handleError("Book already exists with id", http.StatusBadRequest, w)
return
}

jsonStr, err := json.MarshalIndent(output, "", " ")
writer := r.Form.Get("writer")
if writer == "" {
handleError("Missing writer", http.StatusBadRequest, w)
return
}

title := r.Form.Get("title")
if title == "" {
handleError("Missing title", http.StatusBadRequest, w)
return
}

book.Id = id
book.Author = writer
book.Title = title
book.Borrowed = false

if err := book.Save(); err != nil {
handleError("Internal error", http.StatusInternalServerError, w)
return
}

showBookInfo(book, w)
}

func getFilters(r *http.Request) models.Filters {
filters := models.Filters{}
query := r.URL.Query()
title := query.Get("title")
if title != "" {
filters.Title = title
}
writer := query.Get("writer")
if writer != "" {
filters.Writer = writer
}
available := query.Get("available")
if available == "true" {
filters.Available = true
}
return filters
}

func handleError(message string, errorCode int, w http.ResponseWriter) {
jsonStr, err := json.MarshalIndent(message, "", " ")
if err != nil {
fmt.Println(err)
log.Println(err)
w.WriteHeader(http.StatusInternalServerError)
return
}
w.WriteHeader(errorCode)
w.Write(jsonStr)
return
}

func showBookInfo(book models.Book, w http.ResponseWriter) {
jsonStr, err := json.MarshalIndent(book, "", " ")

if err != nil {
handleError("Internal error", http.StatusInternalServerError, w)
return
}

w.WriteHeader(http.StatusOK)
w.Write(jsonStr)
}

func showAllBooksInfo(books []models.Book, w http.ResponseWriter) {
jsonStr, err := json.MarshalIndent(books, "", " ")

if err != nil {
handleError("Internal error", http.StatusInternalServerError, w)
return
}

w.WriteHeader(http.StatusOK)
w.Write(jsonStr)
Expand Down
18 changes: 3 additions & 15 deletions main.go
Original file line number Diff line number Diff line change
@@ -1,13 +1,10 @@
package main

import (
"context"
"fmt"
"log"
"os"

"cloud.google.com/go/datastore"

"acme-books/models"
"acme-books/server"

Expand Down Expand Up @@ -36,25 +33,16 @@ func getEnvWithDefault(key, fallback string) string {
}

func bootstrapBooks() {
ctx := context.Background()
client, _ := datastore.NewClient(ctx, "acme-books")

defer client.Close()

books := []models.Book{
{Id: 1, Author: "George Orwell", Title: "1984", Borrowed: false},
{Id: 2, Author: "George Orwell", Title: "Animal Farm", Borrowed: false},
{Id: 3, Author: "Robert Jordan", Title: "Eye of the world", Borrowed: false},
{Id: 4, Author: "Various", Title: "Collins Dictionary", Borrowed: false},
}

var keys []*datastore.Key

for _, book := range books {
keys = append(keys, datastore.IDKey("Book", book.Id, nil))
}

if _, err := client.PutMulti(ctx, keys, books); err != nil {
fmt.Println(err)
if err := book.Save(); err != nil {
fmt.Println(err)
}
}
}
86 changes: 85 additions & 1 deletion models/book.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,92 @@
package models

import (
"cloud.google.com/go/datastore"
"context"
"fmt"
"google.golang.org/api/iterator"
)

type Book struct {
Id int64
Id int64 `json:"id"`
Title string `json:"title"`
Author string `json:"writer"`
Borrowed bool `json:"borrowed"`
}

func GetBookById(id int64) (Book, error) {
ctx, client := initDatastore()
defer client.Close()

var book Book
key := datastore.IDKey("Book", id, nil)
err := client.Get(ctx, key, &book)

return book, err
}

func GetBooks(filters Filters, order string) ([]Book, error) {
ctx, client := initDatastore()
defer client.Close()

var books []Book

query := datastore.NewQuery("Book")
if filters.Title != "" {
query = query.Filter("Title =", filters.Title)
}
if filters.Writer != "" {
query = query.Filter("Author =", filters.Writer)
}
if filters.Available {
query = query.Filter("Borrowed =", false)
}
if order != "" {
query = query.Order(order)
}

it := client.Run(ctx, query)
for {
var b Book
_, err := it.Next(&b)
if err == iterator.Done {
fmt.Println(err)
break
}
books = append(books, b)
}

return books, nil
}

func (book *Book) Borrow() error {
if book.Borrowed {
return nil
}

book.Borrowed = true
return book.Save()
}

func (book *Book) Return() error {
if !book.Borrowed {
return nil
}

book.Borrowed = false
return book.Save()
}

func (book *Book) Save() error {
ctx, client := initDatastore()
defer client.Close()

_, err := client.Put(ctx, datastore.IDKey("Book", book.Id, nil), book)
return err
}

func initDatastore() (context.Context, *datastore.Client) {
ctx := context.Background()
client, _ := datastore.NewClient(ctx, "acme-books")
return ctx, client
}
7 changes: 7 additions & 0 deletions models/filters.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package models

type Filters struct {
Title string
Writer string
Available bool
}
3 changes: 3 additions & 0 deletions server/router.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,9 @@ func NewRouter() *martini.ClassicMartini {

router.Get("/books", libraryController.ListAll)
router.Get("/books/:id", libraryController.GetByKey)
router.Put("/books/:id/borrow", libraryController.Borrow)
router.Put("/books/:id/return", libraryController.Return)
router.Post("/books", libraryController.Add)

return router
}