Recount-Server/api.go

79 lines
1.8 KiB
Go
Raw Permalink Normal View History

2023-12-30 13:51:59 -08:00
package main
import (
2024-01-11 20:07:47 -08:00
"encoding/json"
"net/http"
2023-12-30 13:51:59 -08:00
2024-01-11 20:07:47 -08:00
//"context"
"fmt"
2023-12-30 13:51:59 -08:00
2024-01-11 20:07:47 -08:00
"github.com/ggicci/httpin"
"github.com/go-chi/chi/v5"
2024-01-01 20:47:34 -08:00
"github.com/rs/zerolog/log"
2024-02-10 10:52:09 -08:00
"nickiel.net/recount_server/db"
"nickiel.net/recount_server/types"
2023-12-30 13:51:59 -08:00
)
2024-01-11 20:07:47 -08:00
const DEFAULT_RESULT_COUNT = 50
2023-12-30 13:51:59 -08:00
type GetTransactionPaginationInput struct {
2024-01-11 20:07:47 -08:00
ResultCount int `in:"query=result_count"`
PageNum int `in:"query=page_num"`
2023-12-30 13:51:59 -08:00
}
func apiRouter() http.Handler {
2024-01-11 20:07:47 -08:00
r := chi.NewRouter()
//r.Use(ApiLoginRequired)
r.With(
httpin.NewInput(GetTransactionPaginationInput{}),
).Get("/get_transactions", getTransactions)
r.Post("/new_transaction", newTransaction)
return r
2023-12-30 13:51:59 -08:00
}
func getTransactions(w http.ResponseWriter, req *http.Request) {
2024-01-11 20:07:47 -08:00
input := req.Context().Value(httpin.Input).(*GetTransactionPaginationInput)
2023-12-30 13:51:59 -08:00
2024-01-11 20:07:47 -08:00
if input.ResultCount == 0 {
input.ResultCount = DEFAULT_RESULT_COUNT
}
2023-12-30 13:51:59 -08:00
2024-02-10 10:52:09 -08:00
transactions := []types.Transaction{}
2023-12-30 13:51:59 -08:00
2024-02-27 18:38:00 -08:00
err := db.GetTransactions(&transactions, input.ResultCount, input.PageNum)
2023-12-31 17:21:09 -08:00
2024-01-11 20:07:47 -08:00
if err != nil {
2023-12-30 13:51:59 -08:00
2024-01-11 20:07:47 -08:00
log.Fatal().
Err(err).
Msg("Fatal error in getTransactions from db_get_transactions")
}
for _, trns := range transactions {
//bytes, err := json.Marshal(trns)
bytes, err := json.MarshalIndent(trns, "", "\t")
if err != nil {
log.Fatal().
Err(err).
Msg("Could not marshal json")
}
fmt.Fprintf(w, string(bytes))
}
2023-12-30 13:51:59 -08:00
}
2024-03-03 20:21:25 -08:00
func HandleNewTransaction(w http.ResponseWriter, req *http.Request) {
log.Fatal().Msg("TODO: new transaction functionality not implemented yet");
// decoder := json.NewDecoder(req.Body)
// var t types.Transaction
// err := decoder.Decode(&t)
// if err != nil {
// log.Fatal().
// Err(err).
// Msg("Could not decode incoming post data")
// }
2024-01-11 20:07:47 -08:00
//fmt.Fprintf(w, "New transaction created for Account: %d, with an Amount of: %s",
// t.Account, t.Amount)
2024-03-03 20:21:25 -08:00
// db.NewTransaction(t)
2023-12-30 13:51:59 -08:00
}