-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
56 lines (46 loc) · 1.28 KB
/
index.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
const express = require("express");
const bodyParser = require("body-parser");
const { PrismaClient } = require("./prisma/generated/client");
const app = express();
const prisma = new PrismaClient();
// Middleware to parse form data
app.use(bodyParser.urlencoded({ extended: true }));
//setting view engine to ejs
app.set("view engine", "ejs");
//route for index page
app.get("/users", async (_req, res) => {
try {
const users = await prisma.user.findMany();
res.render("index", {
users,
title: "EJS example",
header: "Some users",
});
} catch (error) {
console.error("Error fetching users:", error);
res.status(500).json({ error: "Internal Server Error" });
}
});
app.post("/users", async (req, res) => {
const { name, email } = req.body;
if (!name || !email) {
return res.status(400).send("All fields are required.");
}
try {
// Create a new user in the database using Prisma
await prisma.user.create({
data: {
name,
email,
},
});
// Rerender users
res.redirect("/users?success=true");
} catch (error) {
console.error("Error creating user:", error);
res.status(500).send("Internal Server Error");
}
});
app.listen(3000, () => {
console.log("Server is running on port 3000 ");
});