Skip to content

Commit

Permalink
Merge pull request #16 from tunnels-is/datacenter-updates
Browse files Browse the repository at this point in the history
Show datacenters in frontend, generate rows, GET Rows route
  • Loading branch information
zveinn authored Jun 30, 2024
2 parents 5551f03 + 095d856 commit 149184e
Show file tree
Hide file tree
Showing 19 changed files with 305 additions and 51 deletions.
51 changes: 51 additions & 0 deletions .air.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
root = "."
testdata_dir = "testdata"
tmp_dir = "tmp"

[build]
args_bin = []
bin = "./tmp/main"
cmd = "go build -o ./tmp/main ."
delay = 1000
exclude_dir = ["assets", "tmp", "vendor", "testdata"]
exclude_file = []
exclude_regex = ["_test.go"]
exclude_unchanged = false
follow_symlink = false
full_bin = ""
include_dir = []
include_ext = ["go", "tpl", "tmpl", "html"]
include_file = []
kill_delay = "0s"
log = "build-errors.log"
poll = false
poll_interval = 0
post_cmd = []
pre_cmd = []
rerun = false
rerun_delay = 500
send_interrupt = false
stop_on_error = false

[color]
app = ""
build = "yellow"
main = "magenta"
runner = "green"
watcher = "cyan"

[log]
main_only = false
time = false

[misc]
clean_on_exit = false

[proxy]
app_port = 0
enabled = false
proxy_port = 0

[screen]
clear_on_rebuild = false
keep_scroll = true
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
/tmp
95 changes: 94 additions & 1 deletion api.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,99 @@ func ListDatacenters(c echo.Context) error {
return c.JSON(200, dataCenters)
}

func ListRows(c echo.Context) error {
rows := make([]*Row, 0)

var errs []error
action := func(path string) {
if !strings.Contains(path, "row_") {
return
}
data, err := GetObjectFullPath(path)
row := new(Row)
err = json.Unmarshal(data, row)
if err != nil {
errs = append(errs, err)
return
}
rows = append(rows, row)
}

err := GetObjects(basePath, action)
if err != nil {
return c.JSON(500, err)
}

if len(errs) != 0 {
return c.JSON(500, errs)
}

return c.JSON(200, rows)
}

func ListRowsByDatacenter(c echo.Context) error {
dcId := c.Param("id")

dcIdInt, err := strconv.Atoi(dcId)
if err != nil {
return c.JSON(400, err)
}

rows := make([]*Row, 0)

var errs []error
action := func(path string) {
if !strings.Contains(path, "row_") {
return
}
data, err := GetObjectFullPath(path)
row := new(Row)

err = json.Unmarshal(data, row)
if err != nil {
errs = append(errs, err)
return
}

if row.DCID == dcIdInt {
rows = append(rows, row)
}
}

err = GetObjects(basePath, action)
if err != nil {
return c.JSON(500, err)
}

if len(errs) != 0 {
return c.JSON(500, errs)
}

return c.JSON(200, rows)

}

func FindRow(c echo.Context) error {
id := c.Param("id")
idInt, err := strconv.Atoi(id)
if err != nil {
return c.JSON(400, err)
}

data, err := GetObject(RowsPath, RowFile, idInt)
if err != nil {
return c.JSON(500, err)
}

row := new(Row)
err = json.Unmarshal(data, row)
if err != nil {
return c.JSON(500, err)
}

return c.JSON(200, row)
}

func FindDatacenter(c echo.Context) error {
id := c.Param("id")
idInt, err := strconv.Atoi(id)
Expand Down Expand Up @@ -75,4 +168,4 @@ func UserConfigRecieveHandler(c echo.Context) error {
SetConnectedSocket(key, &ConnectedSocket{Config: config})
fmt.Println(globalSocketsM["exampleKey"].Config.Datapoints[0].Axis)
return c.JSON(http.StatusOK, map[string]string{"status": "success"})
}
}
12 changes: 12 additions & 0 deletions frontend/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions frontend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
"@radix-ui/react-tabs": "^1.0.4",
"class-variance-authority": "^0.7.0",
"clsx": "^2.1.1",
"ky": "^1.3.0",
"lucide-react": "^0.395.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
Expand Down
87 changes: 47 additions & 40 deletions frontend/src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,47 +1,54 @@
import React, { useEffect, useState } from 'react';
import ky from 'ky';
import { useEffect, useState } from 'react';
import { API_URL, DatacenterType } from './config/config';
import DatacenterComponent from './components/Datacenter';

const WS_URL = 'ws://localhost:1323/v1/json/dynamic';

function App() {
const [message, setMessage] = useState('');
const [socket, setSocket] = useState<WebSocket | null>(null);

useEffect(() => {
const socket = new WebSocket(WS_URL);
setSocket(socket);

socket.addEventListener('open', () => {
console.log('Connected to server');
socket.send('{"disk":0,"cpu":10,"memory":50,"sub":{"key1":1377}}');
});

socket.addEventListener('message', (event) => {
console.log('Message from server ', event.data);
setMessage(event.data);
});

socket.addEventListener('error', (error) => {
console.error('WebSocket error: ', error);
});

return () => {
socket.close();
};
}, []);

const sendMessage = () => {
if (socket && socket.readyState === WebSocket.OPEN) {
socket.send('Hello World!');
}
};

return (
<div>
<h1>WebSocket Example</h1>
<p>Message from server: {message}</p>
<button onClick={sendMessage}>Send Message</button>
</div>
);
const [socket, setSocket] = useState<WebSocket | null>(null);

useEffect(() => {
const socket = new WebSocket(WS_URL);
setSocket(socket);

socket.addEventListener('open', () => {
console.log('Connected to server');
socket.send('{"disk":0,"cpu":10,"memory":50,"sub":{"key1":1377}}');
});

socket.addEventListener('message', (event) => {
console.log('Message from server ', event.data);
});

socket.addEventListener('error', (error) => {
console.error('WebSocket error: ', error);
});

return () => {
socket.close();
};
}, []);

const [dataCenters, setDataCenters] = useState<Array<DatacenterType>>();

useEffect(() => {
const fetchData = async () => {
const json = await ky.get(`${API_URL}/datacenters`).json();
setDataCenters(json as Array<DatacenterType>);
};
console.log(dataCenters);
fetchData();
}, []);

return (
<div className="m-3">
<h1 className="text-3xl my-3">Name?? Dashboard Stats Logo??</h1>
<div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
{dataCenters?.map((item) => <DatacenterComponent dataCenter={item} />)}
</div>
</div>
);
}

export default App;
30 changes: 30 additions & 0 deletions frontend/src/components/Datacenter.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { API_URL, DatacenterType, RowType } from '@/config/config';
import ky from 'ky';
import { useEffect, useState } from 'react';
import Row from './Row';

const Datacenter = ({ dataCenter }: { dataCenter: DatacenterType }) => {
const [rows, setRows] = useState<RowType[]>();

useEffect(() => {
const getRows = async () => {
const json = await ky
.get(`${API_URL}/rows/datacenter/${dataCenter.ID}`)
.json();
setRows(json as RowType[]);
console.log(json);
};
getRows();
}, []);

return (
<div className="m-3">
Datacenter {dataCenter.Tag}/{dataCenter.ID}
<div className="w-fit p-3 min-h-56 min-w-72 w-full border-2 border-gray-600">
{rows?.map((row) => <Row Row={row} />)}
</div>
</div>
);
};

export default Datacenter;
12 changes: 12 additions & 0 deletions frontend/src/components/Row.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { RowType } from '@/config/config';

const Row = ({ Row }: { Row: RowType }) => {
return (
<div className="my-5 w-full">
Row {Row.Tag}/{Row.ID}
<div className="w-full h-10 border-2 border-gray-600 "></div>
</div>
);
};

export default Row;
14 changes: 14 additions & 0 deletions frontend/src/config/config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
export const API_URL = 'http://localhost:1323/v1/api';

export interface DatacenterType {
ID: number;
Tag: string;
Info: string;
}

export interface RowType {
ID: number;
Tag: string;
Info: string;
DatacenterID: number;
}
7 changes: 3 additions & 4 deletions frontend/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,17 +13,16 @@
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx",
"noImplicitAny": true,

/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true,
"noFallthroughCasesInSwitch": true,
"baseUrl": ".",
"paths": {
"@/*": [
"./src/*"
]
"@/*": ["./src/*"]
}
},
"include": ["src"],
Expand Down
7 changes: 6 additions & 1 deletion main.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ func main() {
e := echo.New()
e.Use(middleware.Logger())
e.Use(middleware.Recover())
e.Use(middleware.CORSWithConfig(middleware.DefaultCORSConfig))

wsV1 := e.Group("/v1/ws")
apiV1 := e.Group("/v1/api")
Expand All @@ -24,6 +25,10 @@ func main() {
apiV1.GET("/datacenters", ListDatacenters)
apiV1.GET("/datacenters/:id", FindDatacenter)

apiV1.GET("/rows", ListRows)
apiV1.GET("/rows/:id", FindRow)
apiV1.GET("/rows/datacenter/:id", ListRowsByDatacenter)

// ws upgrader for react
upgrader := gws.NewUpgrader(&WebSocketHandler{}, &gws.ServerOption{
ParallelEnabled: true,
Expand Down Expand Up @@ -63,7 +68,7 @@ func main() {
})

// user config
e.POST("/v1/user/config", UserConfigRecieveHandler);
e.POST("/v1/user/config", UserConfigRecieveHandler)

e.Logger.Fatal(e.Start(":1323"))
}
Loading

0 comments on commit 149184e

Please sign in to comment.