-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
65 lines (61 loc) · 1.72 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
60
61
62
63
64
65
import express from "express";
import Sequelize, { json } from "sequelize";
import { Customer } from "./models/user.js";
import { config } from "./config/config.js";
const sequelize = new Sequelize(
config.database,
config.username,
config.password,
{
host: config.host,
dialect: config.dialect,
}
);
const app = express();
const port = 3000;
app.use(express.json());
app.get("/", (req, res) => {
res.send("Hello World!");
});
app.listen(port, async () => {
try {
await sequelize.authenticate();
await Customer.sync();
console.log("Connection has been established successfully.");
} catch (error) {
console.error("Unable to connect to the database:", error);
}
console.log(`Server listening on port ${port}`);
});
app.post("/register", async (req, res) => {
try {
const newUser = await Customer.create(req.body);
res.status(201).json({ message: "User created successfully!" });
} catch (error) {
if (error.name === "SequelizeValidationError") {
return res.status(400).json({ error: "Validation errors" });
} else {
console.error(error);
res.status(500).json({ error: "Server error" });
}
}
});
app.get("/users", async (req, res) => {
try {
const users = await Customer.findAll();
res.json(users);
} catch (error) {
console.error(error);
res.status(500).json({ error: "Unable to retrieve users" });
}
});
app.post("/login", async (req, res) => {
const user = await Customer.findOne({
where: { username: req.body.username },
});
if (user.dataValues.password === req.body.password) {
res.status(201).json({ message: "User found", user: user.dataValues });
} else {
res.status(500).json({ message: "Wrong credentials" });
}
});