Skip to content

Commit

Permalink
wip: transaction logic
Browse files Browse the repository at this point in the history
  • Loading branch information
zoedsoupe committed Feb 22, 2024
1 parent 5d5adfd commit 1b8df47
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 9 deletions.
42 changes: 36 additions & 6 deletions internal/transaction.go
Original file line number Diff line number Diff line change
@@ -1,18 +1,19 @@
package internal

import (
"errors"
"net/http"
"time"

"github.com/labstack/echo/v4"
. "github.com/zoedsoupe/exo/changeset"
)

type Transaction struct {
ID int
Value int
CustomerID int
Type [1]string
Description [10]string
Type string
Description string
CreatedAt time.Time
}

Expand All @@ -26,12 +27,41 @@ var client = [5]Client{
{5, "E", 5000 * 100, 0},
}

func MakeTransaction(ID int, Value map[string]interface{}) (Transaction, error) {
func MakeTransaction(ID int, Value map[string]interface{}) (Client, error) {
var t Transaction
var client Client
if ID < 1 || ID > 5 {
return t, errors.New("ID não exitse")
return client, echo.NewHTTPError(http.StatusNotFound, nil)
}

c := Cast[Transaction](Value)
c := Cast[Transaction](Value).
ValidateChange("Type", InclusionValidator{Allowed: []interface{}{"c", "d"}}).
ValidateChange("Description", LengthValidator{Min: 1, Max: 10})

t, err := ApplyNew[Transaction](c)
if err != nil {
return client, echo.NewHTTPError(http.StatusUnprocessableEntity, err.Error())
}

transactions = append(transactions, t)

return client, nil
}

func processTransaction(client *Client, trx Transaction) error {
if trx.Type == "c" {
client.Balance += trx.Value
return nil
}

if !validTransaction(*client, trx.Value) {
return echo.NewHTTPError(http.StatusUnprocessableEntity, nil)
}

client.Balance -= trx.Value
return nil
}

func validTransaction(cilent Client, value int) bool {
return true
}
22 changes: 19 additions & 3 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package main
import (
"flag"
"net/http"
"strconv"

. "github.com/cciuenf/rinha/internal"

Expand All @@ -21,10 +22,25 @@ func main() {
Format: "method=${method}, uri=${uri}, status=${status}\n",
}))

e.GET("/", handleBasic)
e.GET("/clientes/:id/transacoes", handleTransaction)
e.Logger.Fatal(e.Start(*port))
}

func handleBasic(c echo.Context) error {
return c.String(http.StatusOK, "Hello, world!")
func handleTransaction(c echo.Context) error {
param := c.Param("id")

var attrs map[string]interface{}
err := (&echo.DefaultBinder{}).BindBody(c, &attrs)
if err != nil {
return c.JSON(http.StatusInternalServerError, nil)
}

customerID, err := strconv.Atoi(param)
if err != nil {
return c.JSON(http.StatusUnprocessableEntity, nil)
}

t, err := MakeTransaction(customerID, attrs)

return nil
}

0 comments on commit 1b8df47

Please sign in to comment.