@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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@giveback007/util-lib",
3
- "version": "1.0.1",
3
+ "version": "1.0.3",
4
4
  "description": "Utility library",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
package/src/general.ts CHANGED
@@ -1,4 +1,3 @@
1
- // import * as fetchJsonp from 'fetch-jsonp';
2
1
  import type { AnyFnc, AnyObj, Dict, JsType, num, str } from '.';
3
2
  import { isType, objMap, hasKey, clone } from '.';
4
3
 
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
@@ -9,3 +9,4 @@ export * from './object';
9
9
  export * from './string';
10
10
  export * from './test';
11
11
  export * from './time';
12
+ export * from './http';