-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgetSunData.ts
84 lines (77 loc) · 2.03 KB
/
getSunData.ts
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
import axios from "axios";
import { cacheResponse } from "./cache";
import { Log } from "./main";
/*
- https://sunrise-sunset.org/api
- Free API that provides sunset and sunrise times for a given latitude and longitude.
- You may not use this API in a manner that exceeds reasonable request volume.
*/
export const createUrl: (lat: number, lon: number, date: string) => string = (
lat: number,
lon: number,
date: string
) =>
`https://api.sunrise-sunset.org/json?lat=${lat}&lng=${lon}&date=${date}&formatted=0`;
export interface SunDataResponse {
results: {
sunrise: string;
sunset: string;
solar_noon: string;
day_length: number;
civil_twilight_begin: string;
civil_twilight_end: string;
nautical_twilight_begin: string;
nautical_twilight_end: string;
astronomical_twilight_begin: string;
astronomical_twilight_end: string;
};
status: string;
}
export interface SunData {
date: string;
sunrise: string;
sunset: string;
day_length: number;
civil_twilight_begin: string;
civil_twilight_end: string;
}
export const fetchSunData = async (
lat: number,
lon: number,
date: string,
log: Log
): Promise<SunData> => {
try {
log("Fetching Sun data...");
const url = createUrl(lat, lon, date);
const response = await axios.get<SunDataResponse>(url);
log(response.data);
log("");
return {
date: date,
civil_twilight_begin: response.data.results.civil_twilight_begin,
sunrise: response.data.results.sunrise,
civil_twilight_end: response.data.results.civil_twilight_end,
sunset: response.data.results.sunset,
day_length: response.data.results.day_length,
};
} catch (error) {
log(error);
throw new Error("Failed to fetch Sun data");
}
};
export const getSunData: (
lat: number,
lon: number,
date: string,
log: Log
) => Promise<SunData> = async (
lat: number,
lon: number,
date: string,
log: Log
) => {
return await cacheResponse<SunData>(`getSunData-${date}`, async () =>
fetchSunData(lat, lon, date, log)
);
};