-
Notifications
You must be signed in to change notification settings - Fork 36
Expand file tree
/
Copy pathdatabase-server.ts
More file actions
103 lines (87 loc) · 2.16 KB
/
database-server.ts
File metadata and controls
103 lines (87 loc) · 2.16 KB
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
import { SkipServiceBroker } from "@skipruntime/helpers";
import express from "express";
/*
This is the user facing server of the database example
*/
const service = new SkipServiceBroker({
host: "localhost",
control_port: 8081,
streaming_port: 8080,
});
import Database from "better-sqlite3";
type User = {
name: string;
country: string;
};
const db = new Database("./db.sqlite");
const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.get("/users", (_req, res) => {
service
.getStreamUUID("users")
.then((uuid) => {
res.redirect(301, `http://localhost:8080/v1/streams/${uuid}`);
})
.catch((e: unknown) => {
console.log(e);
res.status(500).json("Internal error");
});
});
app.get("/user/:id", (req, res) => {
service
.getArray("users", {}, req.params.id)
.then((user) => {
res.status(200).json(user);
})
.catch((e: unknown) => {
console.log(e);
res.status(500).json("Internal error");
});
});
app.put("/user/:id", (req, res) => {
const key = req.params.id;
const data = req.body as User;
try {
db.prepare(
"INSERT OR REPLACE INTO data (id, object) VALUES ($id, $object)",
).run({
id: key,
object: JSON.stringify(data),
});
service
.update("users", [[key, [data]]])
.then(() => {
res.status(200).json({});
})
.catch((e: unknown) => {
console.log(e);
res.status(500).json("Internal error");
});
} catch (err) {
console.error(err);
res.status(500).json("Internal error");
}
});
app.delete("/user/:id", (req, res) => {
const key = req.params.id;
try {
db.prepare("DELETE FROM data WHERE id = $id").run({ id: key });
service
.deleteKey("users", key)
.then(() => {
res.status(200).json({});
})
.catch((e: unknown) => {
console.log(e);
res.status(500).json("Internal error");
});
} catch (err) {
console.error(err);
res.status(500).json("Internal error");
}
});
const port = 8082;
app.listen(port, () => {
console.log(`Example app listening on port ${port.toString()}`);
});