-
Notifications
You must be signed in to change notification settings - Fork 45
Expand file tree
/
Copy pathhttp.ts
More file actions
49 lines (47 loc) · 1.35 KB
/
http.ts
File metadata and controls
49 lines (47 loc) · 1.35 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
import { COMMON_ERRORS, type Requester } from '@slowreader/api'
import { getEnvironment } from '../environment.ts'
import {
detectNetworkError,
HTTPStatusError,
UserFacingError
} from '../errors.ts'
import { isOutdatedClient } from '../index.ts'
/**
* Takes fetch() wrapper from `@slowreader/api/http` and do the request
* using test’s mock if necessary and checking for network/server errors
* to simplify page’s code.
*/
export async function checkErrors<Params extends object, ResponseJSON>(
requester: Requester<Params, ResponseJSON>,
params: Params,
host: string
): Promise<ResponseJSON> {
let response: Awaited<ReturnType<typeof requester>>
let server = getEnvironment().server
let fetch = typeof server === 'string' ? undefined : server.fetch
try {
response = await detectNetworkError(() => {
return requester(params, { fetch, host })
})
} catch (e) {
getEnvironment().warn(e)
throw e
}
if (!response.ok) {
let text = await response.text()
if (response.status === 400 && text !== 'Invalid request') {
if (text === COMMON_ERRORS.OUTDATED_CLIENT) {
isOutdatedClient.set(true)
}
throw new UserFacingError(text)
} else {
throw new HTTPStatusError(
response.status,
response.url,
text,
response.headers
)
}
}
return response.json()
}