-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathplayer.go
56 lines (45 loc) · 1013 Bytes
/
player.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package main
import (
"context"
"fmt"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/dreamsofcode-io/sqlc/internal/repository"
)
func SellItem(
ctx context.Context,
conn *pgx.Conn,
playerID int64,
itemID uuid.UUID,
) error {
tx, _ := conn.Begin(ctx)
defer tx.Rollback(ctx)
repo := repository.New(tx)
item, err := repo.GetInventoryItem(ctx, repository.GetInventoryItemParams{
PlayerID: playerID,
ItemID: itemID,
})
if err != nil {
return err
}
count, _ := repo.RemoveInventoryItem(ctx, repository.RemoveInventoryItemParams{
PlayerID: playerID,
ItemID: itemID,
})
if count == 0 {
return fmt.Errorf("no item to remove")
}
player, err := repo.IncrPlayerGold(ctx, repository.IncrPlayerGoldParams{
PlayerID: playerID,
Amount: item.Value,
})
if err != nil {
fmt.Println("IncrPlayerGold query failed!")
return err
}
if err = tx.Commit(ctx); err != nil {
return err
}
fmt.Println("Item sold! Player Gold:", player.Gold.Int64)
return nil
}