This commit is contained in:
Jake Kasper
2025-09-02 08:26:16 -05:00
parent 7bb45b64eb
commit 7897c2be58

View File

@@ -49,10 +49,21 @@ router.get('/:propertyId', async (req, res, next) => {
const weatherData = weatherResponse.data;
// Store weather data in cache
// Store weather data in cache (UPSERT). If unique index is missing, fallback to update-then-insert.
const today = new Date().toISOString().split('T')[0];
await pool.query(
`INSERT INTO weather_data
const values = [
propertyId,
today,
Math.round(weatherData.main.temp),
Math.round(weatherData.main.temp_min),
weatherData.main.humidity,
weatherData.wind?.speed || 0,
weatherData.rain?.['1h'] || 0,
weatherData.weather[0].description
];
const upsertSql = `
INSERT INTO weather_data
(property_id, date, temperature_high, temperature_low, humidity, wind_speed, precipitation, conditions)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
ON CONFLICT (property_id, date)
@@ -63,18 +74,48 @@ router.get('/:propertyId', async (req, res, next) => {
wind_speed = EXCLUDED.wind_speed,
precipitation = EXCLUDED.precipitation,
conditions = EXCLUDED.conditions,
created_at = CURRENT_TIMESTAMP`,
[
propertyId,
today,
Math.round(weatherData.main.temp),
Math.round(weatherData.main.temp_min),
weatherData.main.humidity,
weatherData.wind?.speed || 0,
weatherData.rain?.['1h'] || 0,
weatherData.weather[0].description
]
created_at = CURRENT_TIMESTAMP`;
try {
await pool.query(upsertSql, values);
} catch (e) {
// Fallback when unique index is absent: try UPDATE first, then INSERT
const msg = String(e?.message || '');
if (e?.code === '42P10' || msg.includes('no unique or exclusion constraint')) {
const client = await pool.connect();
try {
await client.query('BEGIN');
const upd = await client.query(
`UPDATE weather_data
SET temperature_high = $3,
temperature_low = $4,
humidity = $5,
wind_speed = $6,
precipitation = $7,
conditions = $8,
created_at = CURRENT_TIMESTAMP
WHERE property_id = $1 AND date = $2`,
values
);
if (upd.rowCount === 0) {
await client.query(
`INSERT INTO weather_data
(property_id, date, temperature_high, temperature_low, humidity, wind_speed, precipitation, conditions)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)`,
values
);
}
await client.query('COMMIT');
} catch (inner) {
await client.query('ROLLBACK');
throw inner;
} finally {
client.release();
}
} else {
throw e;
}
}
res.json({
success: true,