This repository has been archived by the owner on Nov 11, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 30
/
api.ts
56 lines (50 loc) · 1.52 KB
/
api.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
import { Forecast, GeoCode } from './constants/types';
declare let process: {
env: {
NODE_ENV: string;
};
};
const CLOUD_FUNCTION_URL =
process.env.NODE_ENV === 'development'
? 'http://localhost:3000/'
: 'https://us-central1-reactjs-weather.cloudfunctions.net/';
const checkStatus = async (response: Response) => {
if (response.status >= 200 && response.status < 300) {
return response;
} else {
let errorJson: any = null;
try {
errorJson = await response.json();
} catch (error) {
throw new Error(response.statusText);
}
if (errorJson.error) {
throw new Error(errorJson.error);
} else {
throw new Error(response.statusText);
}
}
};
const parseJSON = (response: Response) => {
return response
.json()
.then((data) => data)
.catch(() => response);
};
export const getGeocode = (latitude: number, longitude: number, address: string): Promise<GeoCode> => {
const requestUrl =
`${CLOUD_FUNCTION_URL}getGeocode?lat=${latitude}&lon=${longitude}&address=` + encodeURIComponent(address);
return fetch(requestUrl).then(checkStatus).then(parseJSON);
};
export const getWeatherByTime = (
latitude: number,
longitude: number,
time: number,
exclude: string,
units: string
): Promise<Forecast> => {
const requestUrl =
`${CLOUD_FUNCTION_URL}getWeather?lat=${latitude}&lon=${longitude}&time=${time}` +
`&exclude=${encodeURIComponent(exclude)}&units=${encodeURIComponent(units)}`;
return fetch(requestUrl).then(checkStatus).then(parseJSON);
};