set and get now work trough endpoint api
This commit is contained in:
@@ -5,6 +5,7 @@ import (
|
||||
"Portifolio/internal/model"
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
|
||||
_ "github.com/mattn/go-sqlite3"
|
||||
@@ -20,10 +21,35 @@ func AddTradeHandler(db *sql.DB) http.HandlerFunc {
|
||||
|
||||
err := req.Validate()
|
||||
if err != nil {
|
||||
http.Error(w, "invalid json", http.StatusBadRequest)
|
||||
http.Error(w, fmt.Sprintf("failed to validate trade: %s", err), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
// check if currency is in the db.
|
||||
currency, err := database.GetCurrencyByCode(db, req.Currency)
|
||||
if err != nil {
|
||||
http.Error(w, fmt.Sprintf("failed to find currency: %s", err), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
// check if company is in the db.
|
||||
company, err := database.GetCompanyByID(db, req.TickerId)
|
||||
if err != nil {
|
||||
http.Error(w, fmt.Sprintf("failed to find currency: %s", err), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
trade := model.Trade{
|
||||
Ticker: *company,
|
||||
Shares: req.Shares,
|
||||
Product: model.TradeProduct(req.Product),
|
||||
Type: model.TradeType(req.Type),
|
||||
Price: req.Price,
|
||||
Currency: currency,
|
||||
Date: req.Date,
|
||||
}
|
||||
|
||||
database.InsertTrade(db, trade)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -31,13 +57,13 @@ func GetTradeListHandler(db *sql.DB) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
tradeList, err := database.GetTrades(db)
|
||||
if err != nil {
|
||||
http.Error(w, "failed to fetch trades", http.StatusInternalServerError)
|
||||
http.Error(w, fmt.Sprintf("failed to fetch trades:", err), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
if err := json.NewEncoder(w).Encode(tradeList); err != nil {
|
||||
http.Error(w, "failed to encode trades", http.StatusInternalServerError)
|
||||
http.Error(w, fmt.Sprintf("failed to encode trades: %s", err), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user