forked from HSLdevcom/digitransit-ui
-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathapiUtils.js
86 lines (80 loc) · 2.04 KB
/
apiUtils.js
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
85
86
import moment from 'moment-timezone';
import xmlParser from 'fast-xml-parser';
import isEmpty from 'lodash/isEmpty';
import { retryFetch } from './fetchUtils';
export function getUser() {
const options = {
credentials: 'include',
};
return retryFetch('/api/user', options, 2, 200).then(res => res.json());
}
export function getFavourites() {
return retryFetch('/api/user/favourites', {}, 2, 200).then(res => res.json());
}
export function updateFavourites(data) {
const options = {
method: 'PUT',
headers: {
'Content-type': 'application/json',
},
body: JSON.stringify(data),
};
return retryFetch('/api/user/favourites', options, 0, 0).then(res =>
res.json(),
);
}
export function deleteFavourites(data) {
const options = {
method: 'DELETE',
headers: {
'Content-type': 'application/json',
},
body: JSON.stringify(data),
};
return retryFetch('/api/user/favourites', options, 0, 0).then(res =>
res.json(),
);
}
export function getWeatherData(baseURL, time, lat, lon) {
// Round time to next 5 minutes
const remainder = 5 - (time.minute() % 5);
const endtime = time
.add(remainder, 'minutes')
.seconds(0)
.milliseconds(0)
.toISOString();
const searchTime = moment.utc(endtime).format();
return retryFetch(
`${baseURL}&latlon=${lat},${lon}&starttime=${searchTime}&endtime=${searchTime}`,
{},
2,
200,
)
.then(res => res.text())
.then(str => {
const options = {
ignoreAttributes: true,
ignoreNameSpace: true,
};
return xmlParser.parse(str, options);
})
.then(json => {
const data = json.FeatureCollection.member.map(elem => elem.BsWfsElement);
return data;
})
.catch(err => {
throw new Error(`Error fetching weather data: ${err}`);
});
}
export function getRefPoint(origin, destination, location) {
if (!isEmpty(origin)) {
return origin;
}
if (!isEmpty(destination)) {
return destination;
}
if (location && location.hasLocation) {
return location;
}
return null;
}