-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
204 lines (181 loc) · 5.01 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
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
191
192
193
194
195
196
197
198
199
200
201
202
203
204
// index.js
const express = require("express");
const cors = require("cors");
const { Pool } = require("pg");
require("dotenv").config();
const app = express();
const port = process.env.PORT || 5000;
// Middleware
app.use(cors());
app.use(express.json()); // For parsing JSON requests
// PostgreSQL connection pool setup
const pool = new Pool({
connectionString: process.env.DATABASE_URL,
ssl: {
rejectUnauthorized: false, // If self-signed certificates are used
},
});
// Test connection
pool.connect((err) => {
if (err) {
console.error("Error connecting to PostgreSQL", err);
} else {
console.log("Connected to PostgreSQL");
}
});
// Basic route
app.get("/", (req, res) => {
return res.status(200).send("Hello from the backend!");
});
// GET route to fetch all users
app.get("/api/user/:id", async (req, res) => {
const userId = req.params.id;
console.log(userId);
if (!userId) {
return res.status(400).json({ error: "User ID is required" });
}
try {
// Query user details
const userResult = await pool.query(
`SELECT * FROM users WHERE id = $1`,
[userId]
);
if (userResult.rows.length === 0) {
return res.status(404).json({ error: "User not found" });
}
const user = userResult.rows[0];
// Query goals related to the user
const goalsResult = await pool.query(
`SELECT * FROM goals WHERE user_id = $1`,
[userId]
);
const goals = goalsResult.rows;
// Query workouts related to the user
const workoutsResult = await pool.query(
`SELECT * FROM workouts WHERE user_id = $1`,
[userId]
);
const workouts = workoutsResult.rows;
return res.status(200).json({ user, goals, workouts });
} catch (err) {
return res.status(500).json({ error: err.message });
}
});
// Update an existing user's workouts
app.put("/api/user/workouts/:id", async (req, res) => {
const userId = req.params.id;
const { type, duration } = req.body;
try {
// Insert the new workout into the workouts table
const query = `INSERT INTO workouts (user_id, type, duration)
VALUES ($1, $2, $3) RETURNING *`;
const values = [userId, type, duration];
const result = await pool.query(query, values);
if (result.rows.length === 0) {
return res.status(404).json({ message: "User not found" });
}
res.json(result.rows[0]); // Return the updated user
} catch (err) {
console.error(err.message);
res.status(500).send("Server Error");
}
});
// PUT request to update user data
app.put("/api/user/:id", async (req, res) => {
const userId = req.params.id;
const {
name,
email,
bio,
bmi,
age,
weight,
activity_level,
water_intake,
currentweight,
targetweight,
startweight,
targetcalories,
} = req.body;
// Prepare an array of fields to update, only including the ones that are provided
let updateFields = [];
let values = [];
if (name) {
updateFields.push("name = $" + (updateFields.length + 1));
values.push(name);
}
if (email) {
updateFields.push("email = $" + (updateFields.length + 1));
values.push(email);
}
if (bmi) {
updateFields.push("bmi = $" + (updateFields.length + 1));
values.push(bmi);
}
if (age) {
updateFields.push("age = $" + (updateFields.length + 1));
values.push(age);
}
if (weight) {
updateFields.push("weight = $" + (updateFields.length + 1));
values.push(weight);
}
if (activity_level) {
updateFields.push(
"activity_level = $" + (updateFields.length + 1)
);
values.push(activity_level);
}
if (water_intake) {
updateFields.push("water_intake = $" + (updateFields.length + 1));
values.push(water_intake);
}
if (currentweight) {
updateFields.push(
"currentweight = $" + (updateFields.length + 1)
);
values.push(currentweight);
}
if (targetweight) {
updateFields.push("targetweight = $" + (updateFields.length + 1));
values.push(targetweight);
}
if (startweight) {
updateFields.push("startweight = $" + (updateFields.length + 1));
values.push(startweight);
}
if (targetcalories) {
updateFields.push(
"targetcalories = $" + (updateFields.length + 1)
);
values.push(targetcalories);
}
if (bio) {
updateFields.push("bio = $" + (updateFields.length + 1));
values.push(bio);
}
// If no fields are provided to update, return an error
if (updateFields.length === 0) {
return res.status(400).json({ message: "No fields to update" });
}
// Add the user ID to the values array
values.push(userId);
// Build the update query dynamically
const query = `
UPDATE users
SET ${updateFields.join(", ")}
WHERE id = $${values.length}
RETURNING *;
`;
try {
const result = await pool.query(query, values);
res.json(result.rows[0]);
} catch (err) {
console.error("Error updating user:", err);
res.status(500).json({ error: "Internal server error" });
}
});
// Start the server
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});