-
-
Notifications
You must be signed in to change notification settings - Fork 773
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: caches weather with redis & info tooltip (#358)
* feat: caches weather with redis & info tooltip * refactor: literally dropped by 50 lines
- Loading branch information
Showing
5 changed files
with
140 additions
and
79 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,84 +1,124 @@ | ||
import { TRPCError } from "@trpc/server"; | ||
import fetch from "node-fetch"; | ||
import { z } from "zod"; | ||
import { createTRPCRouter, protectedProcedure } from "../trpc"; | ||
|
||
type RawWeatherData = { | ||
properties: { | ||
timeseries: { | ||
data: { | ||
next_12_hours: { | ||
summary: { | ||
symbol_code: string; | ||
}; | ||
}; | ||
instant: { | ||
details: { | ||
air_temperature: number; | ||
}; | ||
}; | ||
}; | ||
}[]; | ||
const hours = z | ||
.object({ | ||
summary: z.object({ | ||
symbol_code: z.string(), | ||
}), | ||
}) | ||
.optional(); | ||
|
||
const timeseriesSchema = z.array( | ||
z.object({ | ||
time: z.string(), | ||
data: z.object({ | ||
next_12_hours: hours, | ||
next_6_hours: hours, | ||
next_1_hours: hours, | ||
instant: z.object({ | ||
details: z.object({ | ||
air_temperature: z.number(), | ||
}), | ||
}), | ||
}), | ||
}), | ||
); | ||
|
||
const weatherDataSchema = z.object({ | ||
temp_max: z.number(), | ||
temp_min: z.number(), | ||
summary: z.string().optional(), | ||
}); | ||
|
||
const input = z.object({ | ||
latitude: z.number(), | ||
longitude: z.number(), | ||
}); | ||
|
||
const getCurrentWeatherData = async ({ | ||
latitude, | ||
longitude, | ||
}: z.infer<typeof input>) => { | ||
const date = new Date().toISOString().slice(0, 10); | ||
const response = await fetch( | ||
`https://api.met.no/weatherapi/locationforecast/2.0/compact?lat=${latitude}&lon=${longitude}`, | ||
{ | ||
headers: { | ||
"User-Agent": `noodle.run (https://github.com/noodle-run/noodle)`, | ||
}, | ||
}, | ||
); | ||
|
||
const data = (await response.json()) as { | ||
properties: { timeseries: unknown }; | ||
}; | ||
|
||
const timeseries = timeseriesSchema | ||
.parse(data.properties.timeseries as z.infer<typeof timeseriesSchema>) | ||
.filter((one) => one.time.includes(date)); | ||
|
||
const temperatures = timeseries.map( | ||
(t) => t.data.instant.details.air_temperature, | ||
); | ||
|
||
let summary; | ||
if (timeseries[0]) { | ||
const { next_12_hours, next_6_hours, next_1_hours } = timeseries[0].data; | ||
const nextData = next_12_hours ?? next_6_hours ?? next_1_hours; | ||
summary = nextData?.summary.symbol_code; | ||
} | ||
|
||
const weatherData = { | ||
summary, | ||
temp_max: Math.max(...temperatures), | ||
temp_min: Math.min(...temperatures), | ||
}; | ||
}; | ||
|
||
type WeatherData = { | ||
temp_max: number; | ||
temp_min: number; | ||
summary: string; | ||
return weatherDataSchema.parse(weatherData); | ||
}; | ||
|
||
export const weatherRouter = createTRPCRouter({ | ||
getWeatherData: protectedProcedure | ||
.input( | ||
z.object({ | ||
latitude: z.number(), | ||
longitude: z.number(), | ||
}), | ||
) | ||
.query(async ({ input }) => { | ||
const { latitude, longitude } = input; | ||
|
||
const response = await fetch( | ||
`https://api.met.no/weatherapi/locationforecast/2.0/compact?lat=${latitude}&lon=${longitude}`, | ||
{ | ||
headers: { | ||
"User-Agent": `noodle.run (https://github.com/noodle-run/noodle)`, | ||
}, | ||
}, | ||
); | ||
|
||
if (!response.ok) { | ||
throw new TRPCError({ | ||
code: "INTERNAL_SERVER_ERROR", | ||
message: "Failed to fetch weather data", | ||
}); | ||
} | ||
.input(input) | ||
.output(weatherDataSchema) | ||
.query(async ({ input, ctx }) => { | ||
const date = new Date().toISOString().slice(0, 10); | ||
const cacheKey = `weather:${date}:${ctx.auth.userId}`; | ||
|
||
const rawWeatherData: RawWeatherData = | ||
(await response.json()) as RawWeatherData; | ||
if (typeof ctx.redis !== "undefined" && typeof ctx.redis !== "string") { | ||
try { | ||
const cachedWeatherData = await ctx.redis.get(cacheKey); | ||
|
||
if (rawWeatherData.properties.timeseries.length < 12) { | ||
throw new TRPCError({ | ||
code: "INTERNAL_SERVER_ERROR", | ||
message: "Partial weather data", | ||
}); | ||
} | ||
if (!cachedWeatherData) { | ||
const weatherData = await getCurrentWeatherData(input); | ||
const secondsUntilMidnight = Math.round( | ||
(new Date().setHours(24, 0, 0, 0) - Date.now()) / 1000, | ||
); | ||
|
||
const temperatures = []; | ||
await ctx.redis.set(cacheKey, JSON.stringify(weatherData), { | ||
ex: secondsUntilMidnight, | ||
}); | ||
return weatherData; | ||
} | ||
|
||
for (const timeseries of rawWeatherData.properties.timeseries) { | ||
temperatures.push(timeseries.data.instant.details.air_temperature); | ||
return weatherDataSchema.parse(cachedWeatherData); | ||
} catch (error) { | ||
throw new TRPCError({ | ||
code: "INTERNAL_SERVER_ERROR", | ||
message: "Failed to fetch cached weather data", | ||
}); | ||
} | ||
} | ||
|
||
const weatherData: WeatherData = { | ||
summary: | ||
rawWeatherData.properties.timeseries[0]!.data.next_12_hours.summary | ||
.symbol_code, | ||
temp_max: Math.max(...temperatures), | ||
temp_min: Math.min(...temperatures), | ||
}; | ||
|
||
return weatherData; | ||
try { | ||
return getCurrentWeatherData(input); | ||
} catch (error) { | ||
throw new TRPCError({ | ||
code: "INTERNAL_SERVER_ERROR", | ||
message: "Failed to fetch weather data", | ||
}); | ||
} | ||
}), | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters