Skip to content

Commit

Permalink
chore : use json package
Browse files Browse the repository at this point in the history
  • Loading branch information
mous1985 committed Oct 9, 2024
1 parent 92aead1 commit f24e91c
Show file tree
Hide file tree
Showing 13 changed files with 182 additions and 74 deletions.
87 changes: 43 additions & 44 deletions api/p/auction/auction.gno
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ package auction
import (
"std"
"strconv"
"strings"
"time"

"gno.land/p/demo/ownable"
Expand Down Expand Up @@ -138,55 +137,55 @@ func (a *Auction) EndAuction() error {
return nil
}

func AuctionsToJSONString(auctions []*Auction) string {
var sb strings.Builder
sb.WriteString("[")
// func AuctionsToJSONString(auctions []*Auction) string {
// var sb strings.Builder
// sb.WriteString("[")

for i, auction := range auctions {
if i > 0 {
sb.WriteString(",")
}
// for i, auction := range auctions {
// if i > 0 {
// sb.WriteString(",")
// }

sb.WriteString(AuctionToJSONString(auction))
}
sb.WriteString("]")
// sb.WriteString(AuctionToJSONString(auction))
// }
// sb.WriteString("]")

return sb.String()
}
// return sb.String()
// }

// AuctionToJSONString returns a Auction formatted as a JSON string
func AuctionToJSONString(auction *Auction) string {
var sb strings.Builder

sb.WriteString("{")
sb.WriteString(`"title":"` + escapeString(auction.Title) + `",`)
sb.WriteString(`"description":"` + escapeString(auction.Description) + `",`)
sb.WriteString(`"begin":"` + strconv.Itoa(int(auction.Begin.Unix())) + `",`)
sb.WriteString(`"deadline":"` + strconv.Itoa(int(auction.End.Unix())) + `",`)
sb.WriteString(`"owner":"` + auction.Ownable.Owner().String() + `",`)
sb.WriteString(`"firstPrice":"` + strconv.Itoa(int(auction.Price)) + `",`)
sb.WriteString(`"bids":` + strconv.Itoa(len(auction.Bids)) + `,`)
sb.WriteString(`"img":"` + escapeString(auction.Img) + `"`)
sb.WriteString("}")

return sb.String()
}

func ErrorToJSONString(err error) string {
if err == nil {
return `{"error": null}`
}
// func AuctionToJSONString(auction *Auction) string {
// var sb strings.Builder

// sb.WriteString("{")
// sb.WriteString(`"title":"` + escapeString(auction.Title) + `",`)
// sb.WriteString(`"description":"` + escapeString(auction.Description) + `",`)
// sb.WriteString(`"begin":"` + strconv.Itoa(int(auction.Begin.Unix())) + `",`)
// sb.WriteString(`"deadline":"` + strconv.Itoa(int(auction.End.Unix())) + `",`)
// sb.WriteString(`"owner":"` + auction.Ownable.Owner().String() + `",`)
// sb.WriteString(`"firstPrice":"` + strconv.Itoa(int(auction.Price)) + `",`)
// sb.WriteString(`"bids":` + strconv.Itoa(len(auction.Bids)) + `,`)
// sb.WriteString(`"img":"` + escapeString(auction.Img) + `"`)
// sb.WriteString("}")

// return sb.String()
// }

// func ErrorToJSONString(err error) string {
// if err == nil {
// return `{"error": null}`
// }

var sb strings.Builder
// var sb strings.Builder

sb.WriteString("{")
sb.WriteString(`"error": "` + escapeString(err.Error()) + `"`)
sb.WriteString("}")
// sb.WriteString("{")
// sb.WriteString(`"error": "` + escapeString(err.Error()) + `"`)
// sb.WriteString("}")

return sb.String()
}
// return sb.String()
// }

// escapeString escapes quotes in a string for JSON compatibility.
func escapeString(s string) string {
return strings.ReplaceAll(s, `"`, `\"`)
}
// // escapeString escapes quotes in a string for JSON compatibility.
// func escapeString(s string) string {
// return strings.ReplaceAll(s, `"`, `\"`)
// }
6 changes: 3 additions & 3 deletions api/p/auction/auction_test.gno
Original file line number Diff line number Diff line change
Expand Up @@ -14,17 +14,17 @@ func TestNewAuction(t *testing.T) {
owner := testutils.TestAddress("owner")
begin := time.Now().Add(1 * time.Hour)
end := time.Now().Add(24 * time.Hour)
minPrice := std.NewCoin("testcoin", 100)
minPrice := int64(100)

auction := NewAuction("Test Auction", owner, "This is a test auction", begin, end, minPrice)
auction := NewAuction("Test Auction", owner, "This is a test auction", begin, end, minPrice, "url")

uassert.Equal(t, "Test Auction", auction.Title, "Auction title mismatch")
uassert.Equal(t, owner, auction.Ownable.Owner(), "Auction owner mismatch")
uassert.Equal(t, "This is a test auction", auction.Description, "Auction description mismatch")
uassert.Equal(t, begin.String(), auction.Begin.String(), "Auction begin time mismatch")
uassert.Equal(t, end.String(), auction.End.String(), "Auction end time mismatch")
uassert.True(t, auction.Price.IsEqual(minPrice), "Auction price mismatch")
uassert.Equal(t, "upcoming", auction.State, "Auction state mismatch")
uassert.Equal(t, "url", auction.Img, "image mismatch")
}

func TestAddBid(t *testing.T) {
Expand Down
1 change: 1 addition & 0 deletions api/p/auction/gno.mod
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
module gno.land/p/demo/auction

require (
gno.land/p/demo/json v0.0.0-latest
gno.land/p/demo/ownable v0.0.0-latest
gno.land/p/demo/testutils v0.0.0-latest
gno.land/p/demo/uassert v0.0.0-latest
Expand Down
107 changes: 107 additions & 0 deletions api/p/auction/json_handler.gno
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
package auction

import (
"std"
"time"

"gno.land/p/demo/json"
"gno.land/p/demo/ufmt"
)

// EncodeAuction encodes an auction as a JSON Node.
func EncodeAuction(auction *Auction) (*json.Node, error) {
node := json.ObjectNode("", map[string]*json.Node{
"title": json.StringNode("title", auction.Title),
"description": json.StringNode("description", auction.Description),
"begin": json.NumberNode("begin", float64(auction.Begin.Unix())),
"deadline": json.NumberNode("deadline", float64(auction.End.Unix())),
"owner": json.StringNode("owner", auction.Ownable.Owner().String()),
"firstPrice": json.NumberNode("firstPrice", float64(auction.Price)),
"bids": json.NumberNode("bids", float64(len(auction.Bids))),
"img": json.StringNode("img", auction.Img),
})

return node, nil
}

// EncodeAuctionList encodes a list of auctions as a JSON array.
func EncodeAuctionList(auctions []*Auction) (*json.Node, error) {
var nodes []*json.Node
for _, auction := range auctions {
auctionNode, err := EncodeAuction(auction)
if err != nil {
return nil, ufmt.Errorf("error encoding auction: %v", err)
}
nodes = append(nodes, auctionNode)
}

arrayNode := json.ArrayNode("", nodes)
return arrayNode, nil
}

// DecodeAuction decodes a JSON Node into an Auction struct.
func DecodeAuction(node *json.Node) (*Auction, error) {
titleNode, err := node.GetKey("title")
if err != nil {
return nil, ufmt.Errorf("missing title: %v", err)
}
title := titleNode.MustString()

descriptionNode, err := node.GetKey("description")
if err != nil {
return nil, ufmt.Errorf("missing description: %v", err)
}
description := descriptionNode.MustString()

beginNode, err := node.GetKey("begin")
if err != nil {
return nil, ufmt.Errorf("missing begin time: %v", err)
}
begin := time.Unix(int64(beginNode.MustNumeric()), 0)

deadlineNode, err := node.GetKey("deadline")
if err != nil {
return nil, ufmt.Errorf("missing deadline time: %v", err)
}
deadline := time.Unix(int64(deadlineNode.MustNumeric()), 0)

ownerNode, err := node.GetKey("owner")
if err != nil {
return nil, ufmt.Errorf("missing owner: %v", err)
}
owner := ownerNode.MustString()

firstPriceNode, err := node.GetKey("firstPrice")
if err != nil {
return nil, ufmt.Errorf("missing firstPrice: %v", err)
}
firstPrice := int64(firstPriceNode.MustNumeric())

imgNode, err := node.GetKey("img")
if err != nil {
return nil, ufmt.Errorf("missing img: %v", err)
}
img := imgNode.MustString()

// Crée l'enchère en utilisant les données décodées
auction := NewAuction(title, std.Address(owner), description, begin, deadline, firstPrice, img)
return auction, nil
}

// ToJSONString converts a JSON Node into a string representation.
func ToJSONString(node *json.Node) (string, error) {
jsonBytes, err := json.Marshal(node)
if err != nil {
return "", err
}
return string(jsonBytes), nil
}

// FromJSONString converts a JSON string into a JSON Node.
func FromJSONString(jsonStr string) (*json.Node, error) {
node, err := json.Unmarshal([]byte(jsonStr))
if err != nil {
return nil, ufmt.Errorf("error parsing JSON: %v", err)
}
return node, nil
}
6 changes: 3 additions & 3 deletions api/r/auction/auction.gno
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ func AddBid(id int, amount int64) string { // amount en int64

// Place the bid in the auction
if err := auction.AddBid(caller, amount); err != nil {
panic(pau.ErrorToJSONString(err))
panic(err.Error())
}

ufmt.Println("Bid placed successfully")
Expand Down Expand Up @@ -138,15 +138,15 @@ func GetAuctions() string {
return "[]"
}

return pau.AuctionsToJSONString(auctionList)
return pau.EncodeAuctionList(auctionList), nil
}

func GetAuctionById(id int) string {
if id >= len(auctionList) || id < 0 {
panic("Invalid auction ID")
}

return pau.AuctionToJSONString(auctionList[id])
return pau.EncodeAuction(auctionList[id])
}

func Render(path string) string {
Expand Down
28 changes: 16 additions & 12 deletions ui/src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { BrowserRouter as Router, Route, Routes } from 'react-router-dom';
import { ChakraProvider, Box } from '@chakra-ui/react'; // Import de Box de Chakra UI
import { ChakraProvider, Box, Flex } from '@chakra-ui/react';
import './App.css';
import { useState } from 'react';
import { GnoWSProvider } from '@gnolang/gno-js-client';
Expand All @@ -11,6 +11,7 @@ import theme from './theme/theme';
import AuctionDetails from './components/organisms/AuctionDetails/AuctionDetails';
import CreateAuctionPage from './pages/CreateAuctionPage';
import Header from './components/molecules/Header/Header';
import Sidebar from './components/molecules/Sidebar/Sidebar'; // Import the Sidebar component
// import UpcomingAuctionsPage from './pages/UpcomingAuctionsPage';
// import OngoingAuctionsPage from './pages/OngoingAuctionsPage';
// import ClosedAuctionsPage from './pages/ClosedAuctionsPage';
Expand Down Expand Up @@ -44,21 +45,24 @@ const App = () => {
<ChakraProvider theme={theme}>
<Router>
<Header />
<Box as="main" className="main-content"> {/* Application de la classe */}
<Routes>
<Route path="/" element={<Home />} />
<Route path="/auction/:id" element={<AuctionDetails />} />
<Route path="/create-auction" element={<CreateAuctionPage />} />
{/* <Route path="/upcoming-auctions" element={<UpcomingAuctionsPage />} />
<Route path="/ongoing-auctions" element={<OngoingAuctionsPage />} />
<Route path="/closed-auctions" element={<ClosedAuctionsPage />} /> */}
</Routes>
</Box>
<Flex>
<Sidebar /> {/* Add the Sidebar component */}
<Box as="main" className="main-content" ml={{ base: 0, md: "200px" }} p={4}>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/auction/:id" element={<AuctionDetails />} />
<Route path="/create-auction" element={<CreateAuctionPage />} />
{/* <Route path="/upcoming-auctions" element={<UpcomingAuctionsPage />} />
<Route path="/ongoing-auctions" element={<OngoingAuctionsPage />} />
<Route path="/closed-auctions" element={<ClosedAuctionsPage />} /> */}
</Routes>
</Box>
</Flex>
</Router>
</ChakraProvider>
</AccountContext.Provider>
</ProviderContext.Provider>
);
};

export default App;
export default App;
12 changes: 6 additions & 6 deletions ui/src/components/molecules/Header/header.types.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { EPostSort, EPostTime } from '../../organisms/Home/home.types.ts';
// import { EPostSort, EPostTime } from '../../organisms/Home/home.types.ts';

export interface IHeaderProps {
setPostSort: (type: EPostSort) => void;
setPostTime: (time: EPostTime) => void;
resetHomepage: () => void;
}
// export interface IHeaderProps {
// setPostSort: (type: EPostSort) => void;
// setPostTime: (time: EPostTime) => void;
// resetHomepage: () => void;
// }
1 change: 0 additions & 1 deletion ui/src/components/molecules/Sidebar/Sidebar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ const Sidebar = () => {

return (
<>
{/* Sidebar */}
<Box
bg="rgba(0, 0, 0, 0.01)"
color="white"
Expand Down
5 changes: 2 additions & 3 deletions ui/src/components/organisms/Home/Home.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,7 @@ import { Box, Text, Button, Grid } from '@chakra-ui/react';
import Config from '../../../config.ts';
import ProviderContext from '../../../context/ProviderContext.ts';
import AccountContext from '../../../context/AccountContext.ts';
import Connect from '../../atoms/Connect/Connect';
import AuctionCard from '../../atoms/Auction/AuctionCard'; // Import AuctionCard
import AuctionCard from '../../atoms/Auction/AuctionCard';
import { IAuction } from '../../atoms/Auction/auction.types';
import { parseAuctionFetchResponse } from './parseAuctionFetchResponse';

Expand Down Expand Up @@ -39,7 +38,7 @@ const Home = () => {
}, []);

const handleCreateAuctionClick = () => {
navigate('/create-auction'); // Redirection vers la page de création d'enchères
navigate('/create-auction');
};

return (
Expand Down
3 changes: 1 addition & 2 deletions ui/src/main.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
// src/main.tsx
import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import { ChakraProvider } from '@chakra-ui/react';
import App from './App.tsx';
import theme from './theme/theme'; // Import the custom theme
import theme from './theme/theme';
import './index.css';

createRoot(document.getElementById('root')!).render(
Expand Down
Empty file added ui/src/pages/AuctionsClosed.tsx
Empty file.
Empty file.
Empty file.

0 comments on commit f24e91c

Please sign in to comment.