-
-
Notifications
You must be signed in to change notification settings - Fork 774
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge branch 'main' into erb3-initial-docker
- Loading branch information
Showing
8 changed files
with
187 additions
and
86 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
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,43 +1,124 @@ | ||
import { TRPCError } from "@trpc/server"; | ||
import fetch from "node-fetch"; | ||
import { z } from "zod"; | ||
import { createTRPCRouter, protectedProcedure } from "../trpc"; | ||
|
||
import { env } from "@/env.mjs"; | ||
const hours = z | ||
.object({ | ||
summary: z.object({ | ||
symbol_code: z.string(), | ||
}), | ||
}) | ||
.optional(); | ||
|
||
import { createTRPCRouter, protectedProcedure } from "../trpc"; | ||
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, | ||
); | ||
|
||
type WeatherData = { | ||
main: { | ||
temp_max: number; | ||
temp_min: number; | ||
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), | ||
}; | ||
weather: { | ||
description: 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; | ||
.input(input) | ||
.output(weatherDataSchema) | ||
.query(async ({ input, ctx }) => { | ||
const date = new Date().toISOString().slice(0, 10); | ||
const cacheKey = `weather:${date}:${ctx.auth.userId}`; | ||
|
||
const response = await fetch( | ||
`https://api.openweathermap.org/data/2.5/weather?lat=${latitude}&lon=${longitude}&appid=${env.OPENWEATHER_API_KEY}&units=metric`, | ||
); | ||
if (typeof ctx.redis !== "undefined" && typeof ctx.redis !== "string") { | ||
try { | ||
const cachedWeatherData = await ctx.redis.get(cacheKey); | ||
|
||
if (!response.ok) { | ||
if (!cachedWeatherData) { | ||
const weatherData = await getCurrentWeatherData(input); | ||
const secondsUntilMidnight = Math.round( | ||
(new Date().setHours(24, 0, 0, 0) - Date.now()) / 1000, | ||
); | ||
|
||
await ctx.redis.set(cacheKey, JSON.stringify(weatherData), { | ||
ex: secondsUntilMidnight, | ||
}); | ||
return weatherData; | ||
} | ||
|
||
return weatherDataSchema.parse(cachedWeatherData); | ||
} catch (error) { | ||
throw new TRPCError({ | ||
code: "INTERNAL_SERVER_ERROR", | ||
message: "Failed to fetch cached weather data", | ||
}); | ||
} | ||
} | ||
|
||
try { | ||
return getCurrentWeatherData(input); | ||
} catch (error) { | ||
throw new TRPCError({ | ||
code: "INTERNAL_SERVER_ERROR", | ||
message: "Failed to fetch weather data", | ||
}); | ||
} | ||
|
||
return response.json() as Promise<WeatherData>; | ||
}), | ||
}); |
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,48 +1,52 @@ | ||
const weatherCodeToEnglish: Record<string, string> = { | ||
clearsky: "🌞 a clear sky", | ||
cloudy: "☁️ clouds", | ||
fair: "⛅ fair", | ||
fair_day: "🌤️ fair day", | ||
fog: "🌫️ fog", | ||
heavyrain: "🌧️ heavy rain", | ||
heavyrainandthunder: "⛈️ heavy rain and thunder", | ||
heavyrainshowers: "🌧️ heavy rain showers", | ||
heavyrainshowersandthunder: "⛈️ heavy rain showers and thunder", | ||
heavysleet: "🌨️ heavy sleet", | ||
heavysleetandthunder: "⛈️ heavy sleet and thunder", | ||
heavysleetshowers: "🌨️ heavy sleet showers", | ||
heavysleetshowersandthunder: "⛈️ heavy sleet showers and thunder", | ||
heavysnow: "❄️ heavy snow", | ||
heavysnowandthunder: "⛈️ heavy snow and thunder", | ||
heavysnowshowers: "❄️ heavy snow showers", | ||
heavysnowshowersandthunder: "⛈️ heavy snow showers and thunder", | ||
lightrain: "🌦️ light rain", | ||
lightrainandthunder: "⛈️ light rain and thunder", | ||
lightrainshowers: "🌦️ light rain showers", | ||
lightrainshowersandthunder: "⛈️ light rain showers and thunder", | ||
lightsleet: "🌧️ light sleet", | ||
lightsleetandthunder: "⛈️ light sleet and thunder", | ||
lightsleetshowers: "🌧️ light sleet showers", | ||
lightsnow: "🌨️ light snow", | ||
lightsnowandthunder: "⛈️ light snow and thunder", | ||
lightsnowshowers: "🌨️ light snow showers", | ||
lightssleetshowersandthunder: "⛈️ light sleet showers and thunder", | ||
lightssnowshowersandthunder: "⛈️ light snow showers and thunder", | ||
partlycloudy: "🌥️ some clouds", | ||
rain: "🌧️ rain", | ||
rainandthunder: "⛈️ rain and thunder", | ||
rainshowers: "🌧️ rain showers", | ||
rainshowersandthunder: "⛈️ rain showers and thunder", | ||
sleet: "🌨️ sleet", | ||
sleetandthunder: "⛈️ sleet and thunder", | ||
sleetshowers: "🌨️ sleet showers", | ||
sleetshowersandthunder: "⛈️ sleet showers and thunder", | ||
snow: "❄️ snow", | ||
snowandthunder: "⛈️ snow and thunder", | ||
snowshowers: "❄️ snow showers", | ||
snowshowersandthunder: "⛈️ snow showers and thunder", | ||
}; | ||
|
||
export const getFormattedWeatherDescription = ( | ||
condition: string | undefined, | ||
) => { | ||
if (!condition) return; | ||
|
||
const weatherToEmoji: Record<string, string> = { | ||
"clear sky": "☀️", | ||
"few clouds": "🌤️", | ||
"scattered clouds": "⛅", | ||
"broken clouds": "☁️", | ||
"overcast clouds": "☁️", | ||
rain: "🌧️", | ||
"light rain": "🌧️", | ||
"moderate rain": "🌧️", | ||
"heavy intensity rain": "🌧️", | ||
"very heavy rain": "🌧️", | ||
"extreme rain": "🌧️", | ||
"freezing rain": "🌨️", | ||
"light intensity shower rain": "🌦️", | ||
"shower rain": "🌧️", | ||
"heavy intensity shower rain": "🌧️", | ||
"ragged shower rain": "🌧️", | ||
"light snow": "❄️", | ||
snow: "❄️", | ||
"heavy snow": "❄️", | ||
sleet: "🌨️", | ||
"shower sleet": "🌨️", | ||
"light rain and snow": "🌨️", | ||
"rain and snow": "🌨️", | ||
"light shower snow": "🌨️", | ||
"shower snow": "🌨️", | ||
"heavy shower snow": "🌨️", | ||
mist: "🌫️", | ||
smoke: "🌫️", | ||
haze: "🌫️", | ||
"sand/ dust whirls": "🌪️", | ||
fog: "🌫️", | ||
sand: "🌫️", | ||
dust: "🌫️", | ||
"volcanic ash": "🌫️", | ||
squalls: "🌬️", | ||
tornado: "🌪️", | ||
clear: "☀️", | ||
clouds: "☁️", | ||
}; | ||
|
||
return `${weatherToEmoji[condition.toLowerCase()] ?? ""} ${condition}`; | ||
if (!condition || !weatherCodeToEnglish[condition]) return; | ||
const weatherDescription = weatherCodeToEnglish[condition]; | ||
return `with ${weatherDescription}`; | ||
}; |