From 2bb365206e1540436d4822301c0104d99d32ec77 Mon Sep 17 00:00:00 2001 From: Derek McQuay Date: Tue, 7 Feb 2017 21:28:37 -0800 Subject: [PATCH] added ability to get single tranx with id --- api.go | 25 ++++++++++++++++++++++--- db.go | 21 +++++++++++++++++++++ 2 files changed, 43 insertions(+), 3 deletions(-) diff --git a/api.go b/api.go index 1392f56..b9abf62 100644 --- a/api.go +++ b/api.go @@ -4,6 +4,7 @@ import ( "encoding/json" "log" "net/http" + "strings" "time" ) @@ -195,14 +196,32 @@ func (s *Server) tranx(w http.ResponseWriter, req *http.Request) { http.Error(w, string(b), http.StatusBadRequest) return case "GET": - tranxs, err := s.db.getTranxs() + searchreq := req.URL.Path[len(prefix["tranx"]):] + if len(searchreq) == 0 { + tranxs, err := s.db.getTranxs() + if err != nil { + log.Printf("%+v", err) + b, _ := json.Marshal(NewFailure(err.Error())) + http.Error(w, string(b), http.StatusInternalServerError) + return + } + json.NewEncoder(w).Encode(tranxs) + return + } + if searchreq[len(searchreq)-1] != '/' { + http.Redirect(w, req, prefix["tranx"]+searchreq+"/", http.StatusMovedPermanently) + return + } + searchReqParsed := strings.Split(searchreq, "/") + t, err := s.db.getTranx(searchReqParsed[0]) if err != nil { log.Printf("%+v", err) b, _ := json.Marshal(NewFailure(err.Error())) - http.Error(w, string(b), http.StatusInternalServerError) + http.Error(w, string(b), http.StatusBadRequest) return } - json.NewEncoder(w).Encode(tranxs) + json.NewEncoder(w).Encode(t) + case "POST": t := tranx{} err := json.NewDecoder(req.Body).Decode(&t) diff --git a/db.go b/db.go index 71087fe..8d7fa89 100644 --- a/db.go +++ b/db.go @@ -127,6 +127,27 @@ func (d *DB) getTranxs() ([]tranx, error) { return results, nil } +func (d *DB) getTranx(i string) (tranx, error) { + result := tranx{} + row := d.db.QueryRow("SELECT id, cost, store, info, date, user_id, category_id FROM tranx WHERE id = $1", + i, + ) + err := row.Scan( + &result.ID, + &result.Cost, + &result.Store, + &result.Info, + &result.Date, + &result.User_ID, + &result.Category_ID, + ) + if err != nil { + return tranx{}, err + } + + return result, nil +} + //func (d *DB) checkOwner(filename, client string) error { // row := d.db.QueryRowx("SELECT client FROM pics WHERE filename = $1", filename) // var owner string