-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
55 lines (51 loc) · 1.62 KB
/
index.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
import {
HolError,
HolInput,
HolRequest,
HolResponse,
HolMetadata,
HolFilter,
Hol,
} from './model'
import { BodyDecoder } from './codec'
import { composeFilters } from './filter_chain'
export function composeHol(hol: Hol, filters: ReadonlyArray<HolFilter>): Hol {
const filter = composeFilters(filters)
return (req) => filter(req, hol)
}
export function fetchToHolRequest(response: Response, metadata?: HolMetadata): HolResponse {
let responseMetadata = metadata ?? new HolMetadata()
return {
response: response,
metadata: responseMetadata,
get statusCode(): number {
return response.status
},
get successful(): boolean {
return response.status >= 200 && response.status < 300
},
get clientError(): boolean {
return response.status >= 400 && response.status < 500
},
get serverError(): boolean {
return response.status >= 500 && response.status < 600
},
get headers(): Headers {
return response.headers
},
body<T>(decoder: BodyDecoder<T>): Promise<T> {
return decoder(response, responseMetadata)
}
}
}
export function hol(request: HolRequest): Promise<HolResponse> {
const clonedMetadata = request.metadata.clone()
return fetch(request.input, request.init).then(response => fetchToHolRequest(response, clonedMetadata), error => {
throw new HolError(error, clonedMetadata)
})
}
export function holToFetch(hol: Hol): (input: HolInput, init?: RequestInit) => Promise<Response> {
return function HolAsFetch(input, init) {
return hol(new HolRequest(input, init, new HolMetadata())).then(response => response.response)
}
}