-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
83 lines (79 loc) · 1.88 KB
/
Copy pathindex.js
File metadata and controls
83 lines (79 loc) · 1.88 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
import express from "express";
import { PrismaClient } from "@prisma/client";
const app = express();
const prisma = new PrismaClient();
app.use(express.json());
//get all users
app.get("/users", async (req, res) => {
const users = await prisma.user.findMany();
res.json(users);
});
//get a user by id
app.get("/users/:id", async (req, res) => {
const { id } = req.params;
try{
const user = await prisma.user.findUnique({
where: { id: parseInt(id) },
});
if (!user) {
return res.status(404).send("User not found");
}
res.json(user);
} catch (error) {
res.status(500).send(error);
}
});
//create a user
app.post("/users", async (req, res) => {
const { name, email, age } = req.body;
try{
const user = await prisma.user.create({
data: { name, email, age },
});
} catch (error) {
res.status(500).send(error);
}
});
//update a user (full update)
app.put("/users/:id", async (req, res) => {
const { id } = req.params;
const { name, email, age } = req.body;
try{
const user = await prisma.user.update({
where: { id: parseInt(id) },
data: { name, email, age },
});
res.json(user);
} catch (error) {
res.status(500).send(error);
}
});
//update a user (partial update)
app.patch("/users/:id", async (req, res) => {
const { id } = req.params;
const { name, email, age } = req.body;
try{
const user = await prisma.user.update({
where: { id: parseInt(id) },
data: { name, email, age },
});
res.json(user);
} catch (error) {
res.status(500).send(error);
}
});
//delete a user
app.delete("/users/:id", async (req, res) => {
const { id } = req.params;
try{
const deletedUser = await prisma.user.delete({
where: { id: parseInt(id) },
});
res.send(`User ${deletedUser.name} `);
} catch (error) {
res.status(404).send(error);
}
});
app.listen(5432, () => {
console.log("Server is running on port 5432");
});