@outseta/react 0.2.0 → 0.2.2

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/src/mutator.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { KyInstance } from "ky";
1
+ import type { OutsetaClient } from "@outseta/api-client";
2
2
 
3
3
  type RequestConfig<T = unknown> = {
4
4
  url: string;
@@ -12,15 +12,16 @@ type RequestConfig<T = unknown> = {
12
12
  * Orval react-query mutator.
13
13
  *
14
14
  * First arg is a request config object `{ url, method, params, signal }`.
15
- * Second arg is a ky instance (provided via the React context/provider).
15
+ * Second arg is a client from `createClient()` (provided via the React
16
+ * context/provider).
16
17
  */
17
- export const customFetch = <T>(
18
+ export const customFetch = async <T>(
18
19
  config: RequestConfig,
19
- client?: KyInstance,
20
+ client?: OutsetaClient,
20
21
  ): Promise<T> => {
21
22
  if (!client) {
22
23
  throw new Error(
23
- "@outseta/react: No client provided. Pass a ky instance from createClient() via the request option.",
24
+ "@outseta/react: No client provided. Pass a client from createClient() via the request option.",
24
25
  );
25
26
  }
26
27
 
@@ -29,17 +30,37 @@ export const customFetch = <T>(
29
30
  const searchParams = params
30
31
  ? new URLSearchParams(
31
32
  Object.entries(params)
32
- .filter(([, v]) => v !== undefined)
33
- .map(([k, v]) => [k, String(v)]),
33
+ .filter(([, value]) => value !== undefined)
34
+ .map(([key, value]) => [key, String(value)]),
34
35
  )
35
36
  : undefined;
36
37
 
37
- return client(url.replace(/^\//, ""), {
38
+ const requestUrl = searchParams?.size
39
+ ? `${url}${url.includes("?") ? "&" : "?"}${searchParams.toString()}`
40
+ : url;
41
+
42
+ const response = await client(requestUrl, {
38
43
  method,
39
- searchParams,
40
- json: data,
44
+ headers: data === undefined
45
+ ? undefined
46
+ : { "Content-Type": "application/json" },
47
+ body: data === undefined ? undefined : JSON.stringify(data),
41
48
  signal,
42
- }).json<T>();
49
+ });
50
+
51
+ if (!response.ok) {
52
+ throw new Error(
53
+ `@outseta/react: Request failed with status ${response.status}`,
54
+ );
55
+ }
56
+
57
+ if (response.status === 204) {
58
+ return undefined as T;
59
+ }
60
+
61
+ return response.headers.get("content-type")?.includes("application/json")
62
+ ? await response.json() as T
63
+ : undefined as T;
43
64
  };
44
65
 
45
66
  export default customFetch;