From b97f3b42e1bad5753728315b5c7ebdacf6f81172 Mon Sep 17 00:00:00 2001 From: Elizabeth Hunt Date: Mon, 6 Jan 2025 23:48:56 -0800 Subject: initial commit --- lib/data-context.ts | 65 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 lib/data-context.ts (limited to 'lib/data-context.ts') diff --git a/lib/data-context.ts b/lib/data-context.ts new file mode 100644 index 0000000..f4c09c7 --- /dev/null +++ b/lib/data-context.ts @@ -0,0 +1,65 @@ +import { createContext } from "react"; +import wmocodes from "./wmocodes.json"; + +interface Weather { + temperature: number; + description: string; + image: string; +} + +interface WhoisUpdate { + name: string; + time: number; +} + +export type Data = { + weather?: Weather; + whois?: WhoisUpdate[]; +}; + +export const DataContext = createContext({}); + +export const fetchWeather = async (): Promise => { + const [latitude, longitude] = await new Promise<[number, number]>((res) => + navigator.geolocation.getCurrentPosition((position) => { + res([position.coords.latitude, position.coords.longitude]); + }) + ); + + const params = new URLSearchParams({ + latitude: latitude.toString(), + longitude: longitude.toString(), + current: ["temperature_2m", "weather_code", "is_day"].join(","), + }).toString(); + const url = `https://api.open-meteo.com/v1/forecast?${params}`; + + return fetch(url) + .then((r) => r.json()) + .then(({ current: { temperature_2m: temp, is_day, weather_code } }) => ({ + temp, + wmo: wmocodes[weather_code as keyof typeof wmocodes][ + is_day ? "day" : "night" + ], + })) + .then(({ wmo, temp }) => ({ + temperature: temp as number, + description: wmo.description, + image: wmo.image, + })); +}; + +export const fetchWhois = async (): Promise => + fetch("https://whois.simponic.xyz/updates") + .then((response) => response.json()) + .then( + (data) => + data + .map((data: WhoisUpdate) => ({ + ...data, + time: new Date(data.time).getTime(), + })) + .sort((a: WhoisUpdate, b: WhoisUpdate) => a.time - b.time) // time should go positive from left to right + .filter((x: WhoisUpdate, i: number, arr: WhoisUpdate[]) => + i > 0 ? x.name !== arr[i - 1].name : true + ) // dedupe updates with the same name + ); -- cgit v1.2.3-70-g09d2