-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathserver.js
219 lines (188 loc) · 6.28 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
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
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
import dotenv from 'dotenv';
import express from 'express';
import cors from 'cors';
import { exec } from 'child_process'; // For executing Python scripts
import db from './config/db.js'; // Import the databaseconnection
dotenv.config();
const app = express();
const PORT = process.env.PORT || 5000;
const scheme_api = process.env.SCHEME_API
app.use(cors({
origin: 'http://localhost:5173', // Allow the frontend origin
methods: 'GET,POST', // Allow specific HTTP methods
credentials: true // Allow cookies to be sent with requests
}));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
// Sample GET request to fetch a user's name by person_id
app.get('/api', (req, res) => {
const query = 'SELECT full_name FROM people WHERE person_id = "P1"'; // Fetch the name of the person with person_id P1
db.query(query, (err, results) => {
if (err) {
console.error('Error fetching name:', err);
res.status(500).send({ error: 'Database query failed' });
} else if (results.length === 0) {
res.status(404).send({ message: 'No records found for person_id P1 in the database' });
} else {
const name = results[0].full_name; // Access the full_name field from the result
res.send({ message: `Hello from ${name}!` });
}
});
});
app.post('/api/login', (req, res) => {
const { username, password, dropdown } = req.body;
if (!username || !password) {
return res.status(400).send({ error: 'Username and password are required' });
}
const query = `
SELECT
users.user_id AS userId,
users.role,
users.district_id AS districtId,
districts.district_name AS district_name,
users.subdivision_id AS subdivisionId,
subdivisions.subdivision_name AS subdivision_name,
users.block_id AS blockId,
blocks.block_name AS block_name
FROM
users
LEFT JOIN
districts ON users.district_id = districts.district_id
LEFT JOIN
subdivisions ON users.subdivision_id = subdivisions.subdivision_id
LEFT JOIN
blocks ON users.block_id = blocks.block_id
WHERE
users.username = ? AND users.password_hash = ?;
`;
db.query(query, [username, password], (err, results) => {
if (err) {
console.error('Error fetching user:', err);
return res.status(500).send({ error: 'Database query failed' });
} else if (results.length === 0) {
return res.status(401).json({ success: false, message: 'Invalid credentials' });
} else {
const user = results[0];
if (user.role === dropdown) {
console.log('Login successful');
console.log('User Data:', user);
const userData = {
userId: user.userId,
role: user.role,
district_name: user.district_name,
districtId: user.districtId,
subdivisionId: user.subdivisionId,
subdivision_name: user.subdivision_name,
blockId: user.blockId,
block_name: user.block_name
};
return res.status(200).json({
success: true,
message: 'Login successful',
userData: userData,
});
} else {
return res.status(400).json({ success: false, message: 'Role mismatch' });
}
}
});
});
// District level api
app.get('/api/subdivisions', (req, res) => {
const districtId = req.query.districtId; // Use req.query for GET requests
if (!districtId) {
return res.status(400).json({ error: "districtId is required" });
}
console.log("districtId:", districtId);
const query = `
SELECT
subdivisions.subdivision_id,
subdivisions.subdivision_name
FROM
subdivisions
WHERE
subdivisions.district_id = ?`;
db.query(query, [districtId], (err, results) => {
if (err) {
return res.status(500).json({ error: "Error fetching subdivisions from database" });
}
if (results.length === 0) {
return res.status(404).json({ error: "No subdivisions found for the given districtId" });
}
res.json({ subdivisionList: results });
});
});
app.get('/api/blocks', (req, res) => {
const subdivisionId = req.query.subdivisionId;
if (!subdivisionId) {
return res.status(400).json({ error: "subdivisionId is required" });
}
console.log("subdivisionId:", subdivisionId);
const query = `
SELECT
blocks.block_id,
blocks.block_name
FROM
blocks
WHERE
blocks.subdivision_id = ?`;
db.query(query, [subdivisionId], (err, results) => {
if (err) {
return res.status(500).json({ error: "Error fetching blocks from database" });
}
if (results.length === 0) {
return res.status(404).json({ error: "No blocks found for the given subdivisionId" });
}
console.log("results contian blocklist", results);
res.json({ blockList: results });
});
});
app.post('/getdata', async (req, res) => {
const url = scheme_api; // External API URL
const data = req.body; // Data sent from the frontend
console.log("datain", data);
try {
const fetchResponse = await fetch(url, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data),
});
const responseData = await fetchResponse.json();
res.status(fetchResponse.status).json({
status: "success",
data: responseData,
});
} catch (error) {
console.error("Error:", error.message);
res.status(500).json({
status: "error",
message: "Internal Server Error",
});
}
});
app.get('/getdata', async (req, res) => {
const url = scheme_api; // External API URL
const data = { blockpeople: "B1" }; // Hardcoded data to send in the request
try {
const fetchResponse = await fetch(url, {
method: 'POST', // Still using POST to interact with the external API
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data),
});
const responseData = await fetchResponse.json();
console.log("API Response:", responseData); // Log the API response in the console
res.status(fetchResponse.status).json({
status: "success",
data: responseData,
});
} catch (error) {
console.error("Error:", error.message);
res.status(500).json({
status: "error",
message: "Internal Server Error",
});
}
});
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});