-
-
Notifications
You must be signed in to change notification settings - Fork 319
/
Copy pathhttp.ts
164 lines (138 loc) · 4.02 KB
/
http.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
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
import storage from './storage'
import spinner from './spinner'
import globalConfig from './config'
import { buildQueryString } from './utils/querystring'
export const SESSION_ID_KEY = 'sessionId'
const baseUrl = globalConfig.apiEndPoint
export interface ErrorResponse {
status: number
// body is either json or text
body?: any
}
export interface RequestOpts {
method?: 'GET' | 'POST'
body?: any
query?: Record<string, unknown>
headers?: Record<string, string>
cache?: RequestCache
mode?: RequestMode
credentials?: RequestCredentials
timeout?: number
}
function addQuerystring(url: string, querystring: string): string {
const prefix = url.indexOf('?') < 0 ? '?' : '&'
const res = url + prefix + querystring
return res
}
// lichess can return either json or text
// for convenience, this wrapper returns a promise with the response body already
// extracted
function request<T>(url: string, type: 'json' | 'text', opts?: RequestOpts, feedback = false): Promise<T> {
let timeoutId: number
function onComplete(): void {
clearTimeout(timeoutId)
if (feedback) spinner.stop()
}
const headers = new Headers({
'X-Requested-With': 'XMLHttpRequest',
'Accept': 'application/vnd.lichess.v' + globalConfig.apiVersion + '+json'
})
const sid = storage.get<string>(SESSION_ID_KEY)
if (sid !== null && sid !== undefined) {
headers.append(SESSION_ID_KEY, sid)
}
const cfg: RequestInit = {
method: 'GET',
credentials: 'include',
}
let fetchTimeoutMs: number | undefined
// merge opts if they are defined
if (opts !== undefined) {
const { headers: optsHeaders, query, timeout, ...optsRest } = opts
fetchTimeoutMs = timeout
if (query) {
const qs = buildQueryString(query)
if (qs !== '') {
url = addQuerystring(url, qs)
}
}
Object.assign(cfg, optsRest)
// allow to remove header if caller specifically mark it as __delete
// (important for cors)
if (optsHeaders) {
Object.keys(optsHeaders)
.forEach(k => {
const v = optsHeaders[k]
if (v !== '__delete') {
headers.set(k, v)
} else {
headers.delete(k)
}
})
}
}
// by default POST and PUT send json except if defined otherwise in caller
if ((cfg.method === 'POST' || cfg.method === 'PUT') && !headers.has('Content-Type')
) {
headers.set('Content-Type', 'application/json; charset=UTF-8')
// always send a json body
if (!cfg.body) {
cfg.body = '{}'
}
}
const fullUrl = url.indexOf('http') > -1 ? url : baseUrl + url
const timeoutPromise = new Promise((_, reject) => {
timeoutId = setTimeout(
() => reject(new Error('Request timeout.')),
fetchTimeoutMs || globalConfig.fetchTimeoutMs
)
})
const respOrTimeout: Promise<Response> = Promise.race([
fetch(fullUrl, { ...cfg, headers }),
timeoutPromise as Promise<Response>
])
if (feedback) {
spinner.spin()
}
return new Promise((resolve, reject) => {
respOrTimeout
.then((r: Response) => {
onComplete()
if (r.ok) {
resolve(r[type]())
}
else {
// assume error is returned as json
// if parsing fails, return text
r.text()
.then((bodyText: string) => {
try {
reject({
status: r.status,
body: JSON.parse(bodyText)
})
} catch (_) {
reject({
status: r.status,
body: r.statusText
})
}
})
}
})
.catch(err => {
onComplete()
// network or timeout error
reject({
status: 0,
body: err.message
})
})
})
}
export function fetchJSON<T>(url: string, opts?: RequestOpts, feedback = false): Promise<T> {
return request<T>(url, 'json', opts, feedback)
}
export function fetchText(url: string, opts?: RequestOpts, feedback = false): Promise<string> {
return request<string>(url, 'text', opts, feedback)
}