This repository was archived by the owner on May 27, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapi.tsx
More file actions
189 lines (166 loc) · 4.58 KB
/
api.tsx
File metadata and controls
189 lines (166 loc) · 4.58 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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
import { get as idbGet, set as idbSet } from 'idb-keyval'
import Analysis from './models/analysis'
import FRCEvent from './models/frc-event'
import Match from './models/match'
import Report from './models/report'
import Schema from './models/schema'
import { User } from './models/user'
import { getJWT, hasValidJWT } from './utils'
const endpoint = 'https://api.pigmice.ga:8081'
export interface Req {
path: string
method: string
body?: string
}
const addRequestToIdb = async (request: Req) => {
const currentRequests = (await idbGet('cachedRequests')) as Req[] | undefined
if (currentRequests === undefined) {
await idbSet('cachedRequests', [request])
return 1
}
await idbSet('cachedRequests', currentRequests.concat(request))
return currentRequests.length + 1
}
const queryAPI = (path: string, method = 'GET', body?: any): Promise<any> =>
fetch(`${endpoint}/${path}`, {
method,
body: JSON.stringify(body),
headers: hasValidJWT(getJWT())
? new Headers({ Authentication: `Bearer ${getJWT()}` })
: undefined
}).catch(async (error: Error) => {
if (method !== 'GET') {
await addRequestToIdb({ path, method, body })
}
throw error
})
const get = <T extends {}>(url: string) => (
cb: (err: Error | null, data: T | null) => any
) => {
let gotten = false
idbGet<T>(url).then(val => {
if (!gotten) {
cb(null, val === undefined ? undefined : val)
}
})
try {
queryAPI(url)
.then(d => d.json())
.then(data => {
cb(null, data)
idbSet(url, data)
gotten = true
})
} catch (error) {
cb(error, undefined)
}
}
const getEvents = () => get<FRCEvent[]>('events')
const getEvent = (eventKey: string) => (
cb: (err: Error | null, data: FRCEvent | null) => any
) => {
get<FRCEvent>(`events/${eventKey}`)((err: Error, data: FRCEvent) => {
if (err) {
cb(err, data)
} else {
if (
data !== undefined &&
data.matches !== undefined &&
data.matches !== null
) {
data.matches = data.matches
.map(value => {
if (!(value.time instanceof Date)) {
value.time = new Date(value.actualTime || value.predictedTime)
}
return value
})
.sort(
(a, b) =>
(a.time === null ? 0 : a.time.getTime()) -
(b.time === null ? 0 : b.time.getTime())
)
}
cb(null, data)
}
})
}
const getEventAnalysis = (eventKey: string) =>
get<Analysis[]>(`events/${eventKey}/analysis`)
const getMatch = (eventKey: string, matchKey: string) =>
get<Match>(`events/${eventKey}/matches/${eventKey}_${matchKey}`)
const getSchema = () => get<Schema>('schema')
const getReporterStats = () =>
get<{ reporter: string; reports: number }[]>('leaderboard')
const getTeamStats = (eventKey: string, team: string) =>
get<Report[]>(`events/${eventKey}/teams/frc${team}/reports`)
const getUsers = () => get<User[]>('users')
const authenticate = (credentials: {
username: string
password: string
}): Promise<string> =>
queryAPI('authenticate', 'POST', credentials).then(async resp => {
if (resp.status < 200 || resp.status >= 300) {
throw new Error(resp.status)
}
return (await resp.json()).jwt
})
const registerUser = (credentials: {
username: string
password: string
}): Promise<string> =>
queryAPI('users', 'POST', credentials).then(resp => {
if (resp.status < 200 || resp.status >= 300) {
throw new Error(resp.status)
}
return null
})
const submitReport = (
team: string,
eventKey: string,
matchKey: string,
stats: { [key: string]: boolean | number },
notes?: string
) =>
queryAPI(
`events/${eventKey}/matches/${eventKey}_${matchKey}/reports`,
'PUT',
{
team,
stats,
notes
}
)
const getAllianceAnalysis = (
eventKey: string,
matchKey: string,
color: string
) =>
get<Analysis[]>(
`events/${eventKey}/matches/${eventKey}_${matchKey}/alliance/${color}/analysis`
)
const deleteUser = (username: string) => queryAPI(`users/${username}`, 'DELETE')
const updateUser = (username: string, user: User) =>
queryAPI(`users/${username}`, 'PUT', user)
const createUser = (user: User) => queryAPI(`users`, 'POST', user)
const getTeamsAtEvent = (eventId: string) =>
get<string[]>(`events/${eventId}/teams`)
export {
getEvents,
getEvent,
getEventAnalysis,
getMatch,
getAllianceAnalysis,
getSchema,
getReporterStats,
getTeamsAtEvent,
getUsers,
deleteUser,
authenticate,
registerUser,
submitReport,
updateUser,
createUser,
queryAPI,
getTeamStats
}