-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
190 lines (170 loc) · 5.63 KB
/
Copy pathserver.js
File metadata and controls
190 lines (170 loc) · 5.63 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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
import express from "express";
import cors from "cors";
import axios from "axios";
import bcrypt from "bcrypt";
import jwt from "jsonwebtoken";
import pkg from "pg";
const { Pool } = pkg;
const app = express();
app.use(express.json());
app.use(cors());
// ----------------------------------------------------------
// DATABASE
// ----------------------------------------------------------
const pool = new Pool({
user: "beyzacavusoglu",
host: "localhost",
database: "chatbot_db",
password: "",
port: 5432,
});
// ----------------------------------------------------------
// JWT CONFIG
// ----------------------------------------------------------
const JWT_SECRET = "supersecretkey";
function authMiddleware(req, res, next) {
const authHeader = req.headers.authorization;
if (!authHeader) return res.status(401).json({ error: "No token provided" });
const token = authHeader.split(" ")[1];
try {
const decoded = jwt.verify(token, JWT_SECRET);
req.userId = decoded.userId;
next();
} catch (err) {
res.status(401).json({ error: "Invalid token" });
}
}
// ----------------------------------------------------------
// AUTH ROUTES
// ----------------------------------------------------------
app.post("/api/signup", async (req, res) => {
const { name, email, password } = req.body;
try {
const hash = await bcrypt.hash(password, 10);
await pool.query(
"INSERT INTO users (name, email, password_hash) VALUES ($1, $2, $3)",
[name, email, hash]
);
res.json({ success: true });
} catch (e) {
res.status(400).json({ error: e.message });
}
});
app.post("/api/login", async (req, res) => {
const { email, password } = req.body;
try {
const result = await pool.query("SELECT * FROM users WHERE email=$1", [email]);
const user = result.rows[0];
if (!user) return res.status(400).json({ error: "User not found" });
const valid = await bcrypt.compare(password, user.password_hash);
if (!valid) return res.status(400).json({ error: "Invalid password" });
const token = jwt.sign({ userId: user.id }, JWT_SECRET, { expiresIn: "2h" });
res.json({
token,
user: { name: user.name, email: user.email },
});
} catch (e) {
res.status(500).json({ error: e.message });
}
});
// ----------------------------------------------------------
// CHAT ROUTE — Connects to FastAPI microservice
// ----------------------------------------------------------
app.post("/api/chat", authMiddleware, async (req, res) => {
try {
const { message, language } = req.body;
// user id as thread_id to maintain chat memory per user
const response = await axios.post("http://127.0.0.1:8000/chat", {
message,
language: language || "English",
thread_id: String(req.userId),
});
const reply =
typeof response.data.reply === "string"
? response.data.reply
: JSON.stringify(response.data.reply);
// Saving message in chat_sessions
await pool.query(
"INSERT INTO chat_sessions (user_id, messages, created_at) VALUES ($1, $2, NOW())",
[req.userId, JSON.stringify({ user: message, bot: reply })]
);
res.json({ reply });
} catch (error) {
console.error("Chat error:", error.response?.data || error.message);
res.status(500).json({ error: "Chat failed" });
}
});
// ----------------------------------------------------------
// HOSPITALS & DOCTORS ROUTES
// ----------------------------------------------------------
app.get("/api/hospitals", async (req, res) => {
try {
const result = await pool.query("SELECT * FROM hospitals ORDER BY id");
res.json(result.rows);
} catch (err) {
res.status(500).json({ error: err.message });
}
});
app.get("/api/doctors/:hospitalId", async (req, res) => {
try {
const { hospitalId } = req.params;
const result = await pool.query(
"SELECT * FROM doctors WHERE hospital_id=$1 ORDER BY id",
[hospitalId]
);
res.json(result.rows);
} catch (err) {
res.status(500).json({ error: err.message });
}
});
// ----------------------------------------------------------
// APPOINTMENTS ROUTES
// ----------------------------------------------------------
app.post("/api/appointments", authMiddleware, async (req, res) => {
const { doctor_id, hospital_id, date, notes } = req.body;
try {
const result = await pool.query(
`INSERT INTO appointments (user_id, doctor_id, hospital_id, date, notes)
VALUES ($1, $2, $3, $4, $5)
RETURNING *`,
[req.userId, doctor_id, hospital_id, date, notes]
);
res.json({ success: true, appointment: result.rows[0] });
} catch (err) {
if (err.code === "23505") {
res.status(400).json({ error: "That doctor already has an appointment at that time." });
} else {
res.status(500).json({ error: err.message });
}
}
});
app.get("/api/appointments", authMiddleware, async (req, res) => {
try {
const result = await pool.query(
`SELECT a.*, d.name AS doctor_name, h.name AS hospital_name
FROM appointments a
JOIN doctors d ON a.doctor_id = d.id
JOIN hospitals h ON a.hospital_id = h.id
WHERE a.user_id=$1
ORDER BY a.date`,
[req.userId]
);
res.json(result.rows);
} catch (err) {
res.status(500).json({ error: err.message });
}
});
app.delete("/api/appointments/:id", authMiddleware, async (req, res) => {
try {
await pool.query("DELETE FROM appointments WHERE id=$1 AND user_id=$2", [
req.params.id,
req.userId,
]);
res.json({ success: true });
} catch (err) {
res.status(500).json({ error: err.message });
}
});
app.listen(3001, () =>
console.log("🚀 Node backend running on http://localhost:3001")
);