summaryrefslogtreecommitdiff
path: root/lib/data-context.ts
blob: 6779b92dcf48f71e966aede480820d281e8c3abf (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
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<Data>({});

export const fetchWeather = async (): Promise<Weather> => {
  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<WhoisUpdate[]> =>
  fetch("https://whois.simponic.xyz/api/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
    );