-
-
Notifications
You must be signed in to change notification settings - Fork 779
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
feat: caches weather with redis & info tooltip #358
Merged
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This is a quite long and confusing line. The code below isn't shorter, but it is more understandable!
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I like this alternative ✅
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
tbh I would rather not need to install another package into the project and for maintenance sake, just use what javascript gave us out of the box, the variable naming is very descriptive of what the operation does so I don't think we necessarily need luxon.