@zap-studio/fetch 0.1.0

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/CHANGELOG.md ADDED
@@ -0,0 +1,15 @@
1
+ # @zap-studio/fetch
2
+
3
+ ## 0.1.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 1644006: Comprehensive description of the initial release features including:
8
+
9
+ - Type-safe HTTP requests with Zod validation
10
+ - Automatic content-type handling
11
+ - Multiple response type support
12
+ - Convenient API methods (GET, POST, PUT, PATCH, DELETE)
13
+ - Flexible error handling
14
+ - Custom FetchError class
15
+ - Full TypeScript support
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Alexandre Trotel
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/package.json ADDED
@@ -0,0 +1,37 @@
1
+ {
2
+ "name": "@zap-studio/fetch",
3
+ "version": "0.1.0",
4
+ "type": "module",
5
+ "private": false,
6
+ "publishConfig": {
7
+ "access": "public"
8
+ },
9
+ "dependencies": {
10
+ "zod": "^4.1.12"
11
+ },
12
+ "devDependencies": {
13
+ "@types/node": "latest",
14
+ "jsdom": "latest",
15
+ "tsdown": "latest",
16
+ "typescript": "latest",
17
+ "vitest": "latest",
18
+ "@zap-studio/typescript-config": "0.0.0",
19
+ "@zap-studio/vitest-config": "0.0.0",
20
+ "@zap-studio/tsdown-config": "0.0.0"
21
+ },
22
+ "exports": {
23
+ ".": "./dist/index.js",
24
+ "./errors": "./dist/errors/index.js",
25
+ "./types": "./dist/types/index.js",
26
+ "./package.json": "./package.json"
27
+ },
28
+ "main": "./dist/index.js",
29
+ "module": "./dist/index.js",
30
+ "types": "./dist/index.d.ts",
31
+ "scripts": {
32
+ "build": "tsdown --config tsdown.config.ts",
33
+ "check-types": "tsc --noEmit",
34
+ "test": "vitest run",
35
+ "test:watch": "vitest --watch"
36
+ }
37
+ }
@@ -0,0 +1,11 @@
1
+ export class FetchError extends Error {
2
+ constructor(
3
+ message: string,
4
+ public status: number,
5
+ public statusText: string,
6
+ public response: Response,
7
+ ) {
8
+ super(message);
9
+ this.name = "FetchError";
10
+ }
11
+ }
package/src/index.ts ADDED
@@ -0,0 +1,126 @@
1
+ import type { z } from "zod";
2
+ import { FetchError } from "./errors";
3
+ import type { FetchConfig, ResponseType } from "./types";
4
+ import { parseResponse, prepareHeadersAndBody } from "./utils";
5
+
6
+ /**
7
+ * Type-safe fetch wrapper with Zod validation
8
+ *
9
+ * @example
10
+ * import { z } from "zod";
11
+ * import { safeFetch } from "@zap-studio/fetch";
12
+ *
13
+ * const UserSchema = z.object({
14
+ * id: z.number(),
15
+ * name: z.string(),
16
+ * email: z.string().email(),
17
+ * });
18
+ *
19
+ * async function getUser(userId: number) {
20
+ * const user = await safeFetch(
21
+ * `https://api.example.com/users/${userId}`,
22
+ * UserSchema,
23
+ * { method: "GET" }
24
+ * );
25
+ * return user; // user is typed as { id: number; name: string; email: string; }
26
+ * }
27
+ */
28
+ export async function safeFetch<
29
+ TResponse,
30
+ TBody = unknown,
31
+ TResponseType extends ResponseType = "json",
32
+ >(
33
+ resource: string,
34
+ responseSchema: z.ZodType<TResponse>,
35
+ config?: FetchConfig<TBody> & {
36
+ throwOnValidationError?: boolean;
37
+ responseType?: TResponseType;
38
+ },
39
+ ): Promise<
40
+ TResponse | z.ZodSafeParseSuccess<TResponse> | z.ZodSafeParseError<TResponse>
41
+ > {
42
+ const {
43
+ body,
44
+ headers,
45
+ throwOnValidationError = true,
46
+ responseType = "json" as TResponseType,
47
+ ...rest
48
+ } = config || {};
49
+
50
+ const { body: preparedBody, headers: preparedHeaders } =
51
+ prepareHeadersAndBody(body, headers);
52
+
53
+ const response = await fetch(resource, {
54
+ ...rest,
55
+ body: preparedBody,
56
+ headers: preparedHeaders,
57
+ });
58
+
59
+ if (!response.ok) {
60
+ throw new FetchError(
61
+ `HTTP ${response.status}: ${response.statusText}`,
62
+ response.status,
63
+ response.statusText,
64
+ response,
65
+ );
66
+ }
67
+
68
+ const data = await parseResponse(response, responseType);
69
+
70
+ return throwOnValidationError
71
+ ? responseSchema.parse(data)
72
+ : responseSchema.safeParse(data);
73
+ }
74
+
75
+ /**
76
+ * Convenience methods for common HTTP verbs
77
+ *
78
+ * @example
79
+ * import { z } from "zod";
80
+ * import { api } from "@zap-studio/fetch";
81
+ *
82
+ * const PostSchema = z.object({
83
+ * id: z.number(),
84
+ * title: z.string(),
85
+ * content: z.string(),
86
+ * });
87
+ *
88
+ * async function fetchPost(postId: number) {
89
+ * const post = await api.get(`https://api.example.com/posts/${postId}`, PostSchema);
90
+ * return post; // post is typed as { id: number; title: string; content: string; }
91
+ * }
92
+ */
93
+ export const api = {
94
+ get: <TResponse>(
95
+ resource: string,
96
+ schema: z.ZodType<TResponse>,
97
+ options?: Omit<RequestInit, "method" | "body">,
98
+ ) => safeFetch(resource, schema, { ...options, method: "GET" }),
99
+
100
+ post: <TResponse, TBody = unknown>(
101
+ resource: string,
102
+ schema: z.ZodType<TResponse>,
103
+ body?: TBody,
104
+ options?: Omit<RequestInit, "method" | "body">,
105
+ ) => safeFetch(resource, schema, { ...options, method: "POST", body }),
106
+
107
+ put: <TResponse, TBody = unknown>(
108
+ resource: string,
109
+ schema: z.ZodType<TResponse>,
110
+ body?: TBody,
111
+ options?: Omit<RequestInit, "method" | "body">,
112
+ ) => safeFetch(resource, schema, { ...options, method: "PUT", body }),
113
+
114
+ patch: <TResponse, TBody = unknown>(
115
+ resource: string,
116
+ schema: z.ZodType<TResponse>,
117
+ body?: TBody,
118
+ options?: Omit<RequestInit, "method" | "body">,
119
+ ) => safeFetch(resource, schema, { ...options, method: "PATCH", body }),
120
+
121
+ delete: <TResponse>(
122
+ resource: string,
123
+ schema: z.ZodType<TResponse>,
124
+ options?: Omit<RequestInit, "method" | "body">,
125
+ ) => safeFetch(resource, schema, { ...options, method: "DELETE" }),
126
+ };
@@ -0,0 +1,23 @@
1
+ export type FetchConfig<TBody> = Omit<RequestInit, "body"> & {
2
+ body?: TBody;
3
+ throwOnValidationError?: boolean;
4
+ };
5
+
6
+ export type ResponseType =
7
+ | "arrayBuffer"
8
+ | "blob"
9
+ | "bytes"
10
+ | "clone"
11
+ | "formData"
12
+ | "json"
13
+ | "text";
14
+
15
+ export type ResponseTypeMap = {
16
+ arrayBuffer: ArrayBuffer;
17
+ blob: Blob;
18
+ bytes: Uint8Array;
19
+ clone: Response;
20
+ formData: FormData;
21
+ json: unknown;
22
+ text: string;
23
+ };
@@ -0,0 +1,104 @@
1
+ import { FetchError } from "../errors";
2
+ import type { ResponseType, ResponseTypeMap } from "../types";
3
+
4
+ export async function parseResponse<TResponseType extends ResponseType>(
5
+ response: Response,
6
+ responseType: TResponseType,
7
+ ): Promise<ResponseTypeMap[TResponseType]> {
8
+ const contentType = response.headers.get("content-type");
9
+
10
+ const parsers: Record<
11
+ ResponseType,
12
+ () => Promise<ResponseTypeMap[ResponseType]>
13
+ > = {
14
+ json: async () => {
15
+ if (!contentType?.includes("application/json")) {
16
+ throw new FetchError(
17
+ "Expected JSON response but received no content type",
18
+ response.status,
19
+ response.statusText,
20
+ response,
21
+ );
22
+ }
23
+ return response.json();
24
+ },
25
+ arrayBuffer: async () => response.arrayBuffer(),
26
+ blob: async () => response.blob(),
27
+ bytes: async () => {
28
+ const buffer = await response.arrayBuffer();
29
+ return new Uint8Array(buffer);
30
+ },
31
+ clone: async () => response.clone(),
32
+ formData: async () => {
33
+ if (!contentType?.includes("multipart/form-data")) {
34
+ throw new FetchError(
35
+ "Expected FormData response but received different content type",
36
+ response.status,
37
+ response.statusText,
38
+ response,
39
+ );
40
+ }
41
+ return response.formData();
42
+ },
43
+ text: async () => {
44
+ if (!contentType?.includes("text/")) {
45
+ throw new FetchError(
46
+ "Expected text response but received different content type",
47
+ response.status,
48
+ response.statusText,
49
+ response,
50
+ );
51
+ }
52
+ return response.text();
53
+ },
54
+ };
55
+
56
+ const parser = parsers[responseType];
57
+ if (!parser) {
58
+ throw new FetchError(
59
+ `Unsupported response type: ${responseType}`,
60
+ response.status,
61
+ response.statusText,
62
+ response,
63
+ );
64
+ }
65
+
66
+ return parser() as Promise<ResponseTypeMap[TResponseType]>;
67
+ }
68
+
69
+ export function prepareHeadersAndBody<TBody = unknown>(
70
+ body: TBody,
71
+ headers: HeadersInit | undefined,
72
+ ): { body: BodyInit | null; headers: HeadersInit | undefined } {
73
+ let preparedBody: BodyInit | null = null;
74
+ let preparedHeaders = headers;
75
+
76
+ // Handle null/undefined body
77
+ if (body === null || body === undefined) {
78
+ return { body: null, headers: preparedHeaders };
79
+ }
80
+
81
+ // Check if body is already a valid BodyInit type
82
+ if (
83
+ body instanceof FormData ||
84
+ body instanceof URLSearchParams ||
85
+ body instanceof Blob ||
86
+ body instanceof ArrayBuffer ||
87
+ body instanceof ReadableStream ||
88
+ typeof body === "string"
89
+ ) {
90
+ preparedBody = body as BodyInit;
91
+ } else if (typeof body === "object") {
92
+ // If body is a plain object, stringify it and set Content-Type
93
+ preparedBody = JSON.stringify(body);
94
+ preparedHeaders = {
95
+ "Content-Type": "application/json",
96
+ ...headers,
97
+ };
98
+ } else {
99
+ // Handle other primitive types by converting to string
100
+ preparedBody = String(body);
101
+ }
102
+
103
+ return { body: preparedBody, headers: preparedHeaders };
104
+ }