-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
250 lines (224 loc) · 7.45 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
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
import express from "express";
import cors from "cors";
import compression from "compression"; //for optimizations
import { PrismaClient } from "@prisma/client";
const app = express();
const PORT = 8900;
const prisma = new PrismaClient();
app.use(
cors({
origin: "https://master-frontend-31-12-2024.netlify.app",
methods: ["GET", "POST", "PUT", "DELETE"],
credentials: true,
})
);
app.use(compression()); //for optimization
app.use(express.static("public"));
app.use(express.json({ limit: "100mb" }));
// City ---------------------------------------------------------------------------
app.get("/city", async (req, res) => {
try {
const cities = await prisma.city.findMany();
return res.json(cities);
} catch (err) {
console.log(err);
return res.json(err);
}
});
// Station -------------------------------------------------------------------------
app.get("/station", async (req, res) => {
try {
const stations = await prisma.station.findMany();
return res.json(stations);
} catch (err) {
console.log(err);
return res.json(err);
}
});
app.get("/soil_measurements", async (req, res) => {
try {
const soil_measurements = await prisma.soilMeasurement.findMany({
include: {
station: true,
soil_attribute: true,
},
});
return res.json(soil_measurements);
} catch (err) {
console.log(err);
return res.json(err);
}
});
// Soil Measurements
app.post("/bulk_soil_measurements", async (req, res) => {
console.log("Received data:", req.body); // Log incoming data for debugging
const records = req.body.map((record) => {
// Ensure value is a valid float (number)
let validValue = parseFloat(record.value);
if (isNaN(validValue)) {
console.log(
`Invalid value for station ${record.station_id} and soil attribute ${record.soil_attribute_id}: ${record.value}`
);
validValue = null; // Set to null or handle it accordingly if invalid
}
// Ensure date_time is in ISO-8601 format
let formattedDate = record.date_time
? new Date(record.date_time).toISOString() // Converts to ISO-8601 format (e.g., 2024-04-07T09:00:00.000Z)
: undefined; // If date_time is not provided, set it to undefined (let PostgreSQL handle it)
// Return the processed record
return {
station_id: record.station_id,
soil_attribute_id: record.soil_attribute_id,
date_time: formattedDate, // Ensure correct format or undefined
value: validValue, // Ensure value is a valid float or null
};
});
try {
await prisma.soilMeasurement.createMany({
data: records,
skipDuplicates: true,
});
res.send("Soil data inserted/updated successfully");
} catch (err) {
console.error("Error inserting soil data:", err);
res.status(500).send("Server error");
}
});
// Climate Measurements
app.get("/climate_measurements", async (req, res) => {
try {
const climate_measurements = await prisma.climateMeasurement.findMany({
include: {
station: true,
climate_attribute: true,
},
});
return res.json(climate_measurements);
} catch (err) {
console.log(err);
return res.json(err);
}
});
// Bulk Insert for Soil Measurements
app.post("/bulk_soil_measurements", async (req, res) => {
console.log("Received data:", req.body); // Log incoming data for debugging
const records = req.body.map((record) => {
// Ensure value is parsed as a float (number)
let validValue = parseFloat(record.value);
// If value is not a valid number, log the invalid value and set it to null or handle it
if (isNaN(validValue)) {
console.log(
`Invalid value for station ${record.station_id} and soil attribute ${record.soil_attribute_id}: ${record.value}`
);
validValue = null; // You can choose to set it to null or handle it accordingly
}
// Ensure date_time is in ISO-8601 format
let formattedDate = record.date_time
? new Date(record.date_time).toISOString() // Converts to ISO-8601 format
: undefined; // If date_time is missing, set it to undefined
// Ensure the value is being passed
if (validValue === undefined) {
console.log(
`Value missing for station ${record.station_id}, soil attribute ${record.soil_attribute_id}`
);
}
// If the value is valid, return the processed record
return {
station_id: record.station_id,
soil_attribute_id: record.soil_attribute_id,
date_time: formattedDate, // Ensure correct format or undefined
value: validValue, // Ensure value is a valid float or null
};
});
// After processing, ensure the data is in the correct format
console.log("Processed records:", records);
try {
// Insert the records into the database
await prisma.soilMeasurement.createMany({
data: records,
skipDuplicates: true,
});
res.send("Soil data inserted/updated successfully");
} catch (err) {
console.error("Error inserting soil data:", err);
res.status(500).send("Server error");
}
});
// Bulk Insert for Climate Measurements
app.post("/bulk_climate_measurements", async (req, res) => {
const records = req.body.map((record) => {
// Ensure value is a valid float
let validValue = parseFloat(record.value);
// Check if value is NaN (invalid)
if (isNaN(validValue)) {
validValue = null; // Set to null or handle it accordingly
}
// Ensure date_time is in ISO-8601 format
let formattedDate = record.date_time
? new Date(record.date_time).toISOString() // Converts to ISO-8601 format (e.g., 2024-04-07T09:00:00.000Z)
: undefined; // If date_time is not provided, set it to undefined (let PostgreSQL handle it)
return {
station_id: record.station_id,
climate_attribute_id: record.climate_attribute_id,
date_time: formattedDate, // Ensure correct format or undefined
value: validValue, // Pass as a float
};
});
try {
await prisma.climateMeasurement.createMany({
data: records,
skipDuplicates: true,
});
res.send("Climate data inserted/updated successfully");
} catch (err) {
console.error("Error inserting climate data:", err);
res.status(500).send("Server error");
}
});
// Users --------------------------------------------------------------------------
app.get("/users", async (req, res) => {
try {
const users = await prisma.user.findMany();
return res.json(users);
} catch (err) {
console.log(err);
return res.json(err);
}
});
app.post("/users", async (req, res) => {
const { password, first_name, last_name, phone_number, email, role } =
req.body;
try {
await prisma.user.create({
data: {
password,
first_name,
last_name,
phone_number,
email,
role,
},
});
return res.status(201).json({ message: "Record inserted successfully" });
} catch (err) {
console.error("Error inserting record:", err);
return res.status(500).json({ error: "Error inserting record" });
}
});
// Photos ---------------------------------------------------------------------
app.get("/photos", async (req, res) => {
try {
const photos = await prisma.photo.findMany();
return res.json(photos);
} catch (err) {
console.error(err);
return res.status(500).json({ error: "Error fetching photos" });
}
});
app
.listen(8800, () => {
console.log("Server running on port 8900");
})
.on("error", (err) => {
console.error("Error starting server:", err);
});