@bryanochoa/custom-fetch-api 1.0.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/README.md ADDED
@@ -0,0 +1,110 @@
1
+ #Fetch API personalizado
2
+
3
+ Este proyecto utiliza la funcionalidad nativa del FETCH API para realizar solicitudes HTTP de manera personalizada. El objetivo es proporcionar una interfaz sencilla y flexible para interactuar con APIs externas, manejando configuraciones específicas adaptando algunas de las peticiones http más comunes.
4
+
5
+ Cabe aclarar que este proyecto no es un reemplazo completo del FETCH API, sino una capa adicional que facilita su uso en ciertos escenarios. El proyecto sigue en construcción y esta sujeto a cambios y mejoras continuas. De momento, se encuentra en una fase inicial de desarrollo y se espera que evolucione con el tiempo.
6
+
7
+ ### Instalación
8
+
9
+ ```bash
10
+ npm install @shadow/fetch
11
+
12
+ ```
13
+
14
+ ### pnpm
15
+
16
+ ```bash
17
+ pnpm add @shadow/fetch
18
+
19
+ ```
20
+
21
+ ### yarn
22
+
23
+ ```bash
24
+ yarn add @shadow/fetch
25
+
26
+ ```
27
+
28
+ - Ejemplo de uso
29
+
30
+ Petición GET:
31
+
32
+ ```
33
+ const data = await makeApiRequest('https://api.example.com/data');
34
+ ```
35
+
36
+ Petición POST:
37
+
38
+ ```
39
+ const data = await makeApiRequest('https://api.example.com/data', {
40
+ method: 'POST',
41
+
42
+ body: {
43
+ key: 'value'
44
+ }
45
+ });
46
+ Petición PUT:
47
+
48
+ ```
49
+
50
+ const data = await makeApiRequest('https://api.example.com/data', {
51
+ method: 'PUT',
52
+ body: {
53
+ key: 'value'
54
+ }
55
+ });
56
+
57
+ Si tu peticion maneja tokens de autenticación, puedes incluirlos en el objeto de configuración:
58
+
59
+ ```
60
+ const data = await makeApiRequest('https://api.example.com/data', {
61
+ method: 'GET',
62
+ token:"Bearer your_token_here"
63
+ });
64
+ ```
65
+
66
+ La petición incluira el token en el encabezado de autorización de la solicitud HTTP.
67
+
68
+ También es posible agregar searchParams a la URL de la solicitud:
69
+
70
+ ```
71
+ const data = await makeApiRequest('https://api.example.com/data', {
72
+ method: 'GET',
73
+ searchParams: {
74
+ param1: 'value1',
75
+ param2: 'value2'
76
+ }
77
+ });
78
+
79
+ ```
80
+
81
+ - Tipado de peticiciones
82
+
83
+ Al utilizar TypeScript, se puede tipar la respuesta de la solicitud HTTP para obtener un mejor control sobre los datos recibidos. Por ejemplo:
84
+
85
+ ```
86
+ interface ApiResponse {
87
+ id: number;
88
+ name: string;}
89
+
90
+ Petición GET:
91
+
92
+ ```
93
+
94
+ const data = await makeApiRequest<ApiResponse>('https://api.example.com/data');
95
+
96
+ console.log(data.id);
97
+
98
+ ```
99
+ Esa es una forma de asegurarse de que la respuesta de la solicitud HTTP cumpla con la estructura esperada y evitar errores en tiempo de ejecución.
100
+
101
+
102
+
103
+ Al utilizar searchParams, la URL final de la solicitud incluirá los parámetros de búsqueda especificados: 'https://api.example.com/data?param1=value1&param2=value2'. Cabe aclarar que si se desea agregar searchParams a la URL, se debe pasar un objeto con las propiedades y valores correspondientes.
104
+
105
+ Por ultimo, se puede cambiar el content-type de la solicitud HTTP, por defecto se utiliza 'application/json', pero puede cambiarse a formData en caso de que la petición requiera enviar archivos
106
+
107
+ No lo mencione en ejemplos anteriores pero por defecto, las peticiones de tipo POST,PUT,PATCH la propiedad body se convierte automáticamente a JSON por ende es obligatorio que para esta propiedad se pase un objeto, de lo contrario la petición fallara.
108
+
109
+ El proyecto se encuentra en constante desarrollo y se espera que se agreguen más funcionalidades y mejoras en el futuro.
110
+ ```
@@ -0,0 +1,12 @@
1
+ //#region src/fetch.d.ts
2
+ type RequestMethods = "POST" | "DELETE" | "GET" | "PATCH" | "PUT";
3
+ interface RequestOptions {
4
+ method?: RequestMethods;
5
+ body?: any;
6
+ token?: string;
7
+ contentType?: "application/json" | "FormData";
8
+ searchParams?: Record<string, any>;
9
+ }
10
+ declare function makeApiRequest<T>(url: string, options?: RequestOptions): Promise<T>;
11
+ //#endregion
12
+ export { makeApiRequest };
package/dist/index.mjs ADDED
@@ -0,0 +1,24 @@
1
+ //#region src/fetch.ts
2
+ async function makeApiRequest(url, options) {
3
+ const headers = new Headers();
4
+ let optionRequest = { headers };
5
+ let partialUrl = "";
6
+ if (options) {
7
+ const { body, token = "", method = "GET", contentType = "application/json", searchParams } = options;
8
+ optionRequest.method = method;
9
+ if (method != "GET" && method != "DELETE" && body && contentType == "application/json") {
10
+ headers.append("Content-Type", "application/json");
11
+ optionRequest.body = JSON.stringify(body);
12
+ } else optionRequest.body = body;
13
+ if (token) headers.append("Authorization", `Bearer token`);
14
+ if (searchParams) {
15
+ const urlWithSearchParams = new URLSearchParams();
16
+ for (const [key, value] of Object.entries(searchParams)) urlWithSearchParams.append(key, value.toString());
17
+ partialUrl = urlWithSearchParams.toString();
18
+ }
19
+ }
20
+ const finalUrl = partialUrl != "" ? url.concat("?", partialUrl) : url;
21
+ return await (await fetch(finalUrl, optionRequest)).json();
22
+ }
23
+ //#endregion
24
+ export { makeApiRequest };
package/package.json ADDED
@@ -0,0 +1,38 @@
1
+ {
2
+ "name": "@bryanochoa/custom-fetch-api",
3
+ "type": "module",
4
+ "version": "1.0.0",
5
+ "description": "fetch API personalizado",
6
+ "author": "Bryan Ochoa <bryanjm96@gmail.com>",
7
+ "license": "MIT",
8
+ "homepage": "https://github.com/author/library#readme",
9
+ "repository": {
10
+ "type": "git",
11
+ "url": "git+https://github.com/author/library.git"
12
+ },
13
+ "bugs": {
14
+ "url": "https://github.com/author/library/issues"
15
+ },
16
+ "exports": {
17
+ ".": "./dist/index.mjs",
18
+ "./package.json": "./package.json"
19
+ },
20
+ "files": [
21
+ "dist"
22
+ ],
23
+ "scripts": {
24
+ "build": "tsdown",
25
+ "dev": "tsdown --watch",
26
+ "test": "vitest",
27
+ "typecheck": "tsc --noEmit",
28
+ "release": "bumpp",
29
+ "prepublishOnly": "pnpm run build"
30
+ },
31
+ "devDependencies": {
32
+ "@types/node": "^26.1.1",
33
+ "bumpp": "^11.1.0",
34
+ "tsdown": "^0.22.5",
35
+ "typescript": "^7.0.2",
36
+ "vitest": "^4.1.10"
37
+ }
38
+ }