forked from hplush/slowreader
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttp.ts
More file actions
55 lines (51 loc) · 1.64 KB
/
http.ts
File metadata and controls
55 lines (51 loc) · 1.64 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
import type { Requester } from '@slowreader/api'
import { getEnvironment } from '../environment.ts'
import { commonMessages as t } from '../messages/index.ts'
/**
* Network/server error on server’s HTTP API request.
*/
export class HTTPRequestError extends Error {
constructor(text: string) {
super(text)
this.name = 'HTTPRequestError'
Error.captureStackTrace(this, this.constructor)
}
static is(error: unknown): error is HTTPRequestError {
return (
typeof error === 'object' &&
error !== null &&
'name' in error &&
error.name === 'HTTPRequestError'
)
}
}
/**
* 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 requester(params, { fetch, host })
} catch (e) {
if (e instanceof Error) getEnvironment().warn(e)
throw new HTTPRequestError(t.get().networkError)
}
if (!response.ok) {
let text = await response.text()
if (response.status === 400 && text !== 'Invalid request') {
throw new HTTPRequestError(text)
} else {
getEnvironment().warn(new Error(`Response ${response.status}: ${text}`))
throw new HTTPRequestError(t.get().internalError)
}
}
return response.json()
}