2023-12-30 13:51:59 -08:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
|
|
|
"net/http"
|
|
|
|
"encoding/json"
|
|
|
|
|
|
|
|
//"context"
|
|
|
|
"fmt"
|
|
|
|
"log"
|
|
|
|
|
|
|
|
_ "github.com/lib/pq"
|
|
|
|
"github.com/jmoiron/sqlx"
|
|
|
|
"github.com/go-chi/chi/v5"
|
|
|
|
"github.com/ggicci/httpin"
|
|
|
|
)
|
|
|
|
|
|
|
|
const DEFAULT_RESULT_COUNT = 50;
|
|
|
|
|
|
|
|
type GetTransactionPaginationInput struct {
|
|
|
|
ResultCount int `in:"query=result_count"`
|
|
|
|
PageNum int `in:"query=page_num"`
|
|
|
|
}
|
|
|
|
|
|
|
|
func apiRouter() http.Handler {
|
|
|
|
r := chi.NewRouter()
|
|
|
|
//r.Use(ApiLoginRequired)
|
|
|
|
r.With(
|
|
|
|
httpin.NewInput(GetTransactionPaginationInput{}),
|
|
|
|
).Get("/get_transactions", getTransactions)
|
|
|
|
r.Post("/new_transaction", newTransaction)
|
|
|
|
return r
|
|
|
|
}
|
|
|
|
|
|
|
|
func getTransactions(w http.ResponseWriter, req *http.Request) {
|
|
|
|
db, err := sqlx.Connect("postgres", "user=rcntuser password=Devel@pmentPa$$w0rd host=10.0.0.183 dbname=Borealis sslmode=disable")
|
|
|
|
if err != nil {
|
|
|
|
log.Fatal(err)
|
|
|
|
}
|
|
|
|
defer db.Close()
|
|
|
|
|
|
|
|
input := req.Context().Value(httpin.Input).(*GetTransactionPaginationInput)
|
|
|
|
|
|
|
|
if input.ResultCount == 0 {
|
|
|
|
input.ResultCount = DEFAULT_RESULT_COUNT
|
|
|
|
}
|
|
|
|
|
|
|
|
transactions := []Transaction{}
|
|
|
|
|
|
|
|
err = db.Select(&transactions,
|
|
|
|
"SELECT trns_id, trns_amount, trns_description, " +
|
|
|
|
"trns_account, trns_bucket, trns_date " +
|
|
|
|
"FROM rcnt.transactions ORDER BY trns_id DESC " +
|
|
|
|
fmt.Sprintf("OFFSET %d ROWS FETCH NEXT %d ROWS ONLY",
|
|
|
|
input.PageNum, input.ResultCount))
|
|
|
|
|
|
|
|
for _, trns := range transactions {
|
|
|
|
//bytes, err := json.Marshal(trns)
|
|
|
|
bytes, err := json.MarshalIndent(trns, "", "\t")
|
|
|
|
if err != nil {
|
|
|
|
log.Fatal(err)
|
|
|
|
}
|
|
|
|
fmt.Fprintf(w, string(bytes))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func newTransaction(w http.ResponseWriter, req *http.Request) {
|
2023-12-30 14:10:41 -08:00
|
|
|
decoder := json.NewDecoder(req.Body)
|
|
|
|
var t Transaction
|
|
|
|
err := decoder.Decode(&t)
|
2023-12-30 13:51:59 -08:00
|
|
|
if err != nil {
|
|
|
|
log.Fatal(err)
|
|
|
|
}
|
2023-12-30 14:10:41 -08:00
|
|
|
fmt.Fprintf(w, "New transaction created for Account: %d, with an Amount of: %s",
|
|
|
|
t.Account, t.Amount)
|
2023-12-30 13:51:59 -08:00
|
|
|
}
|