@giveback007/util-lib 1.0.1 → 1.0.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/src/general.ts +0 -1
- package/src/http.ts +68 -0
- package/src/index.ts +1 -0
package/package.json
CHANGED
package/src/general.ts
CHANGED
package/src/http.ts
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import { Dict } from "./@types";
|
|
2
|
+
|
|
3
|
+
export function joinParamsToUrl(
|
|
4
|
+
url: string,
|
|
5
|
+
searchParams: Dict<string | number | undefined | null>,
|
|
6
|
+
) {
|
|
7
|
+
const u = new URL(url);
|
|
8
|
+
Object.entries(searchParams).forEach(([key, value]) =>
|
|
9
|
+
value !== undefined
|
|
10
|
+
&&
|
|
11
|
+
value !== null
|
|
12
|
+
&&
|
|
13
|
+
u.searchParams.append(key, value as string)
|
|
14
|
+
);
|
|
15
|
+
|
|
16
|
+
return u.href;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export async function fetchJSON<T = any, ErrData = any>(
|
|
20
|
+
url: string,
|
|
21
|
+
options: {
|
|
22
|
+
method?: 'GET',
|
|
23
|
+
searchParams?: Dict<string | number | undefined | null>,
|
|
24
|
+
headers?: Dict<string>
|
|
25
|
+
} = {}
|
|
26
|
+
) {
|
|
27
|
+
const _url = joinParamsToUrl(url, options.searchParams || {});
|
|
28
|
+
delete options.searchParams;
|
|
29
|
+
|
|
30
|
+
if (!options.method) options.method = 'GET';
|
|
31
|
+
if (!options.headers) options.headers = {};
|
|
32
|
+
options.headers['Accept'] = 'application/json';
|
|
33
|
+
|
|
34
|
+
type Opt = Omit<typeof options, 'searchParams'>
|
|
35
|
+
let res: Response | undefined = undefined;
|
|
36
|
+
try {
|
|
37
|
+
res = await fetch(_url, options as Opt);
|
|
38
|
+
if (res.ok && res.status === 200) {
|
|
39
|
+
return {
|
|
40
|
+
ok: true as true,
|
|
41
|
+
data: await res.json() as T,
|
|
42
|
+
err: undefined, res
|
|
43
|
+
};
|
|
44
|
+
} else {
|
|
45
|
+
let data: ErrData | undefined;
|
|
46
|
+
try {
|
|
47
|
+
data = await res.json()
|
|
48
|
+
} catch {
|
|
49
|
+
data = undefined;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
return {
|
|
53
|
+
ok: false as false,
|
|
54
|
+
data: data as ErrData | undefined,
|
|
55
|
+
err: new Error(res.statusText),
|
|
56
|
+
res
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
} catch(err) {
|
|
60
|
+
console.log(err)
|
|
61
|
+
return {
|
|
62
|
+
ok: false as false,
|
|
63
|
+
data: undefined,
|
|
64
|
+
err: err instanceof Error ? err : new Error(err as any),
|
|
65
|
+
res
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
}
|
package/src/index.ts
CHANGED