-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsegment.js
More file actions
88 lines (77 loc) · 2.84 KB
/
segment.js
File metadata and controls
88 lines (77 loc) · 2.84 KB
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
87
88
const request = require('./request')
const Cache = require('./cache')
const cache = new Cache()
function get(token, athleteId, segmentId, startDate) {
return cache.get({
key: `athlete-${athleteId}-segment-${segmentId}-${startDate}`,
createFn: () => new Segment(token, athleteId, segmentId, startDate)
})
}
class Segment {
constructor(token, athleteId, segmentId, startDate) {
this.token = token
this.athleteId = athleteId
this.segmentId = segmentId
this.startDate = startDate
}
effort() {
if (!this.effortPromise) {
const search = {
athlete_id: this.athleteId,
per_page: 1,
start_date_local: this.startDate,
end_date_local: this.startDate ? (new Date()).toISOString() : undefined
};
this.effortPromise = request.get(this.token, `/api/v3/segments/${this.segmentId}/all_efforts`, search)
.then(efforts => efforts.length > 0 ? efforts[0] : null)
}
return this.effortPromise
}
stream() {
if (!this.streamPromise) {
this.streamPromise = this.effort().then(effort => {
return effort
? request.get(this.token, `/api/v3/segment_efforts/${effort.id}/streams/latlng?series_type=time&resolution=medium`)
: Promise.resolve(null)
})
}
return this.streamPromise
}
map(mapFn) {
return this.stream().then(stream => {
const latLngData = stream ? stream.find(s => s.type === 'latlng') : null;
const timeData = stream ? stream.find(s => s.type === 'time') : null;
if (latLngData && timeData) {
const firstTime = timeData.data[0]
return latLngData.data.map((latLng, i) => {
let point = mapFn({ lat: latLng[0], lng: latLng[1] })
point.time = timeData.data[i] - firstTime
return point
})
} else {
return null
}
})
}
route() {
if (!this.routePromise) {
this.routePromise = request.get(this.token, `/api/v3/segments/${this.segmentId}/streams/latlng?series_type=time&resolution=high`)
}
return this.routePromise
}
mapRoute(mapFn) {
return this.route().then(stream => {
const latLngData = stream ? stream.find(s => s.type === 'latlng') : null;
if (latLngData) {
return latLngData.data.map(latLng => {
return mapFn({ lat: latLng[0], lng: latLng[1] })
})
} else {
return null
}
})
}
}
module.exports = {
get
}