-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
99 lines (82 loc) · 2.58 KB
/
index.ts
File metadata and controls
99 lines (82 loc) · 2.58 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
import express, { Request, Response } from "express";
import { PrismaClient } from "@prisma/client";
const app = express();
app.use(express.json());
const prisma = new PrismaClient();
app.get("/", (req: Request, res: Response) => {
res.send("Hello World");
});
app.post("/", async (req: Request, res: Response) => {
const { username, email, password } = req.body;
const user = await prisma.user.create({
data: { username:username, email:email, password:password },
});
res.json(user);
});
app.post("/createManyUsers", async (req: Request, res: Response) => {
const {userList} = req.body;
const users = await prisma.user.createMany({
data:userList,
});
res.json(users);
});
app.post("/createManyCars", async (req: Request, res: Response) => {
const {carList} = req.body;
const cars = await prisma.car.createMany({
data:carList,
});
res.json(cars);
});
app.get("/users", async (req: Request, res: Response) => {
const users = await prisma.user.findMany({include:{cars:true}});
res.json(users);
});
app.get("/byid/:id", async (req: Request, res: Response) => {
const id = req.params.id;
const user = await prisma.user.findUnique({
where: { id:Number(id) },
});
res.json(user);
});
app.put("/", async (req: Request, res: Response) => {
const { id,username } = req.body;
const updatedUser=await prisma.user.update({
where: { id:id },
data: { username:username },
});
res.json(updatedUser);
});
app.delete("/:id", async (req: Request, res: Response) => {
const id = req.params.id;
const deletedUser = await prisma.user.delete({
where: { id:Number(id) },
});
res.json(deletedUser);
});
app.post("/createUsersWithCars", async (req: Request, res: Response) => {
const {username, email, password, cars} = req.body;
try {
const result = await prisma.$transaction(async (tx) => {
const user = await tx.user.create({
data: {
username,
email,
password,
cars: {
create: cars.map((car: {model: string; year: number}) => ({
model: car.model,
year: car.year
}))
}
}
});
return user;
});
res.json(result);
} catch (error) {
res.status(500).json({ error: "Failed to create user with cars" });
}
});
app.listen(3001, () => {
console.log("Server is running on port 3001");
});