-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
59 lines (53 loc) · 1.49 KB
/
server.js
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
const { prisma, express } = require("./common");
const app = express();
app.use(express.json());
const PORT = 3014;
app.listen(PORT, () => {
console.log(`Server is running on port: ${PORT}`);
});
app.get("/users", async (req, res) => {
try {
const users = await prisma.user.findMany();
res.status(200).json(users);
} catch (error) {
res.status(500).json({ error: "Couldnt retrieve user" });
}
});
app.get("/users/:id", async (req, res) => {
const { id } = req.params;
try {
const user = await prisma.user.findUnique({
where: { id: Number(id) },
include: { playlists: true },
});
if (!user) {
return res.status(404).json({ error: "User not found" });
}
res.status(200).json(user);
} catch (error) {
res.status(500).json({ error: "Error while retrieving user" });
}
});
app.post("/users/:id/playlists", async (req, res) => {
const { id } = req.params;
const { name, description } = req.body;
if (!name || !description) {
return res.status(400).json({ error: "Name and description required" });
}
try {
const user = await prisma.user.findUnique({ where: { id: Number(id) } });
if (!user) {
return res.status(404).json({ error: "User not found?" });
}
const newPlaylist = await prisma.playlist.create({
data: {
name,
description,
ownerId: user.id,
},
});
res.status(201).json(newPlaylist);
} catch (error) {
res.status(500).json({ error: "Error occurred.." });
}
});