Skip to content

Commit 9af8628

Browse files
committed
feat: serious backend stuff (no auth yet)
1 parent 5082853 commit 9af8628

11 files changed

Lines changed: 277 additions & 125 deletions

File tree

server/prisma/schema.prisma

Lines changed: 32 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,17 +2,44 @@
22
// learn more about it in the docs: https://pris.ly/d/prisma-schema
33

44
generator client {
5-
provider = "prisma-client-js"
5+
provider = "prisma-client-js"
66
previewFeatures = ["referentialIntegrity"]
77
}
88

99
datasource db {
10-
provider = "mysql"
11-
url = env("DATABASE_URL")
10+
provider = "mysql"
11+
url = env("DATABASE_URL")
1212
referentialIntegrity = "prisma"
1313
}
1414

1515
model User {
16-
id Int @id @default(autoincrement())
17-
name String?
16+
id Int @id @default(autoincrement())
17+
username String
18+
password String
19+
email String
20+
devices Device[]
21+
changes Change[]
22+
createdAt DateTime @default(now())
23+
updatedAt DateTime @updatedAt
24+
}
25+
26+
model Change {
27+
id Int @id @default(autoincrement())
28+
changes String // JSON stringified { staged: '...', unstaged: '...' }
29+
device Device @relation(fields: [deviceId], references: [id])
30+
deviceId Int
31+
createdAt DateTime @default(now())
32+
updatedAt DateTime @updatedAt
33+
owner User? @relation(fields: [ownerId], references: [id])
34+
ownerId Int?
35+
}
36+
37+
model Device {
38+
id Int @id @default(autoincrement())
39+
name String
40+
owner User @relation(fields: [ownerId], references: [id])
41+
ownerId Int
42+
changes Change[]
43+
createdAt DateTime @default(now())
44+
updatedAt DateTime @updatedAt
1845
}

server/src/db.ts

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
import { PrismaClient } from "@prisma/client";
2+
3+
const db = new PrismaClient();
4+
5+
export default db;

server/src/index.ts

Lines changed: 5 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
import { PrismaClient } from "@prisma/client";
21
import express from "express";
32

43
const PORT = process.env.PORT || 3001;
@@ -7,34 +6,11 @@ const app = express();
76

87
app.use(express.json());
98

10-
let data: any = null;
11-
12-
const prisma = new PrismaClient();
13-
14-
async function main() {
15-
const allUsers = await prisma.user.findMany();
16-
console.log("users", allUsers);
17-
}
18-
19-
app.post(`/`, async (req, res) => {
20-
data = req.body;
21-
console.log("server: save data=", Object.keys(data.diff));
22-
res.json({ success: true });
23-
});
24-
25-
app.get(`/`, async (req, res) => {
26-
console.log("server: get data=", Object.keys(data.diff));
27-
res.json(data);
28-
});
29-
30-
const server = app.listen(PORT, () => {
31-
main()
32-
.catch((e) => {
33-
throw e;
34-
})
35-
.finally(async () => {
36-
await prisma.$disconnect();
37-
});
9+
app.use("/auth", require("./routes/auth"));
10+
app.use("/users", require("./routes/users"));
11+
app.use("/devices", require("./routes/devices"));
12+
app.use("/changes", require("./routes/changes"));
3813

14+
app.listen(PORT, () => {
3915
console.log(`🚀 Server ready at: http://localhost:${PORT}`);
4016
});

server/src/middleware/auth.ts

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
function authMdw(request: any, response: any, next: any) {
2+
next();
3+
}
4+
5+
export default authMdw;

server/src/routes/auth.ts

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
import { Router } from "express";
2+
import authMdw from "../middleware/auth";
3+
4+
const router = Router();

server/src/routes/changes.ts

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
// SEND CHANGES, SAVE CHANGES, CLEAN CHANGES
2+
import { Router } from "express";
3+
import db from "../db";
4+
import authMdw from "../middleware/auth";
5+
6+
const router = Router();
7+
8+
router.get("/", authMdw, async (req, res) => {
9+
try {
10+
const { deviceId } = req.body;
11+
12+
const userId = 1; // JSONWEBTOKEN
13+
const user = await db.user.findUnique({
14+
where: {
15+
id: userId,
16+
},
17+
});
18+
if (!user) throw new Error("No user found");
19+
20+
const changes = await db.change.findMany({
21+
where: {
22+
ownerId: user.id,
23+
deviceId,
24+
},
25+
take: 1,
26+
orderBy: {
27+
createdAt: "desc",
28+
},
29+
});
30+
31+
res.json({ diff: JSON.parse(changes[0].changes) });
32+
} catch (error) {
33+
res.status(500).json({ msg: "Something went wrong in the server!" });
34+
}
35+
});
36+
37+
router.post("/", authMdw, async (req, res) => {
38+
try {
39+
const { diff, deviceId } = req.body;
40+
41+
const userId = 1; // JSONWEBTOKEN
42+
const user = await db.user.findUnique({
43+
where: {
44+
id: userId,
45+
},
46+
});
47+
if (!user) throw new Error("User not found");
48+
49+
await db.change.create({
50+
data: {
51+
changes: JSON.stringify(diff),
52+
ownerId: userId,
53+
deviceId: deviceId,
54+
},
55+
});
56+
57+
res.json({ success: true });
58+
} catch (err) {
59+
res.status(500).json({ msg: "Something went wrong in the server!" });
60+
}
61+
});

server/src/routes/devices.ts

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
import { Router } from "express";
2+
import db from "../db";
3+
import authMdw from "../middleware/auth";
4+
5+
const router = Router();
6+
7+
router.post("/", authMdw, async (req, res) => {
8+
try {
9+
const userId = 1; // JSONWEBTOKEN
10+
const user = await db.user.findUnique({
11+
where: {
12+
id: userId,
13+
},
14+
});
15+
if (!user) throw new Error("User not found");
16+
17+
const { name } = req.body;
18+
19+
const devices = await db.device.create({
20+
data: {
21+
owner: {
22+
connect: { id: user.id },
23+
},
24+
name,
25+
},
26+
});
27+
28+
res.json({ success: true });
29+
} catch (error) {
30+
res.status(500).json({ msg: "Something went wrong in the server!" });
31+
}
32+
});
33+
34+
router.get("/", authMdw, async (req, res) => {
35+
try {
36+
const userId = 1; // JSONWEBTOKEN
37+
const user = await db.user.findUnique({
38+
where: {
39+
id: userId,
40+
},
41+
});
42+
if (!user) throw new Error("User not found");
43+
44+
const devices = await db.device.findMany({
45+
where: {
46+
ownerId: user.id,
47+
},
48+
});
49+
50+
res.json({ devices });
51+
} catch (error) {
52+
res.status(500).json({ msg: "Something went wrong in the server!" });
53+
}
54+
});

server/src/routes/users.ts

Whitespace-only changes.

solid/src/App.tsx

Lines changed: 14 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -8,47 +8,50 @@ interface Device {
88

99
function App() {
1010
const [devices, { mutate, refetch }] = createResource<Device[]>(async () => {
11-
const response = await fetch("http://localhost:3001/api/devices", {
11+
const response = await fetch("http://localhost:3001/devices", {
1212
method: "GET",
13-
body: JSON.stringify({
14-
userId: 1,
15-
}),
13+
// headers: JSONWEBTOKEN
1614
});
1715
const connectedDevices = await response.json();
1816
return connectedDevices;
1917
});
2018

19+
/**
20+
* Send changes to the server.
21+
* They can be accessed from any connected device by pressing 'Receive'
22+
* button of the device that they were sent from (nice english i got there)
23+
*/
2124
const onSend = () => {
2225
console.log("onSend");
2326
vscodeApi.postMessage({
2427
type: "send",
2528
});
2629
};
2730

28-
const onReceive = () => {
31+
/**
32+
* Each device in devices list have a 'Receive' button
33+
* which allows to download last changes from that device and apply them
34+
*/
35+
const onReceive = (deviceId: string) => {
2936
console.log("onReceive");
3037
vscodeApi.postMessage({
3138
type: "receive",
39+
deviceId,
3240
});
3341
};
3442

3543
return (
3644
<div>
3745
<p>Devices</p>
3846

39-
<div>
40-
<button onClick={onSend}>SEND</button>
41-
<button onClick={onReceive}>RECEIVE</button>
42-
</div>
43-
4447
<div>
4548
<For each={devices()} fallback={<span>Empty</span>}>
4649
{(device) => (
4750
<div>
4851
<span>{`${device.name} - ${device.id}`}</span>
4952
<div>
5053
<button onClick={onSend}>SEND</button>
51-
<button onClick={onReceive}>RECEIVE</button>
54+
<button onClick={() => onReceive(device.id)}>RECEIVE</button>
5255
</div>
5356
</div>
5457
)}

0 commit comments

Comments
 (0)