-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
72 lines (64 loc) · 1.6 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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import type { Params, AnyObject } from 'pinejs-client-core';
import { PinejsClientCore } from 'pinejs-client-core';
export type { PinejsClientCore } from 'pinejs-client-core';
interface BackendParams {
/** The browser fetch API implementation or a compatible one */
fetch?: typeof fetch;
}
export class RequestError extends Error {
public code = 'PineClientFetchRequestError';
constructor(
public body: string,
public status: number,
public responseHeaders: object,
) {
super(`Request error: ${body}`);
}
}
export default class PineFetch extends PinejsClientCore<PineFetch> {
constructor(
params: Params,
public backendParams: BackendParams,
) {
super(params);
if (
typeof backendParams?.fetch !== 'function' &&
typeof fetch !== 'function'
) {
throw new Error(
'No fetch implementation provided and native one not available',
);
}
}
async _request({
url,
body,
...options
}: {
url: string;
body?: AnyObject;
} & AnyObject) {
const normalizedBody =
body == null
? null
: typeof body === 'object'
? JSON.stringify(body)
: body;
// Assign to a variable first, otherwise browser fetch errors in case the context is different.
const fetchImplementation = this.backendParams?.fetch ?? fetch;
const response = await fetchImplementation(url, {
...options,
body: normalizedBody,
});
if (response.status >= 400) {
let responseBody = 'Unknown error';
try {
responseBody = await response.text();
} catch {
// empty
}
throw new RequestError(responseBody, response.status, response.headers);
}
return response.json();
}
}