use-fetch-error 1.0.0 → 1.0.1

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.
Files changed (3) hide show
  1. package/README.md +20 -0
  2. package/package.json +9 -1
  3. package/src/index.js +52 -97
package/README.md ADDED
@@ -0,0 +1,20 @@
1
+ # Use-fetch-error
2
+
3
+ ## A library for error handling with [error, result] tuples using a `useFetchError()` function.
4
+
5
+ ### Example usage:
6
+
7
+ ```javascript
8
+ (async () => {
9
+ const validURL = "https://jsonplaceholder.typicode.com/posts/1";
10
+ const invalidURL = "https://url-invalid.com";
11
+
12
+ const [error, data] = await useFetchError(invalidURL);
13
+
14
+ if (error) {
15
+ console.error("An error occurred:", error);
16
+ } else {
17
+ console.log("Data received:", data);
18
+ }
19
+ })();
20
+ ```
package/package.json CHANGED
@@ -1,6 +1,14 @@
1
1
  {
2
2
  "name": "use-fetch-error",
3
- "version": "1.0.0",
3
+ "version": "1.0.1",
4
+ "description": "A library for error handling with [error, result] tuples using a useFetch() function.",
5
+ "keywords": [
6
+ "javascript",
7
+ "fetch",
8
+ "handle error"
9
+ ],
10
+ "author": "llatzer",
11
+ "license": "MIT",
4
12
  "main": "src/index.js",
5
13
  "browser": "src/index.js"
6
14
  }
package/src/index.js CHANGED
@@ -1,103 +1,58 @@
1
- "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
- var __generator = (this && this.__generator) || function (thisArg, body) {
12
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
13
- return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
14
- function verb(n) { return function (v) { return step([n, v]); }; }
15
- function step(op) {
16
- if (f) throw new TypeError("Generator is already executing.");
17
- while (g && (g = 0, op[0] && (_ = 0)), _) try {
18
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
19
- if (y = 0, t) op = [op[0] & 2, t.value];
20
- switch (op[0]) {
21
- case 0: case 1: t = op; break;
22
- case 4: _.label++; return { value: op[1], done: false };
23
- case 5: _.label++; y = op[1]; op = [0]; continue;
24
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
25
- default:
26
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
27
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
28
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
29
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
30
- if (t[2]) _.ops.pop();
31
- _.trys.pop(); continue;
32
- }
33
- op = body.call(thisArg, _);
34
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
35
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
36
- }
37
- };
38
- Object.defineProperty(exports, "__esModule", { value: true });
39
- exports.useFetchError = useFetchError;
40
- var symbol = Symbol("result");
41
- Function.prototype[symbol] = function () {
42
- var args = [];
43
- for (var _i = 0; _i < arguments.length; _i++) {
44
- args[_i] = arguments[_i];
45
- }
46
- try {
47
- var result = this.apply(this, args);
48
- return [null, result];
49
- }
50
- catch (error) {
51
- return [error, undefined];
52
- }
1
+ const symbolResult = Symbol("result");
2
+
3
+ /**
4
+ * Extiende el prototipo de `Function` para incluir un método
5
+ * que maneja errores y devuelve una tupla `[error, result]`.
6
+ *
7
+ * @param {...any[]} args - Los argumentos que se pasarán a la función.
8
+ * @returns {[any, any]} Una tupla con `null` y el resultado si la función se ejecuta correctamente,
9
+ * o el error y `undefined` si ocurre una excepción.
10
+ */
11
+ Function.prototype[symbolResult] = function (...args) {
12
+ try {
13
+ const result = this.apply(this, args);
14
+ return [null, result];
15
+ } catch (error) {
16
+ return [error, undefined];
17
+ }
53
18
  };
54
- Promise.prototype[symbol] = function () {
55
- return __awaiter(this, void 0, void 0, function () {
56
- var result, error_1;
57
- return __generator(this, function (_a) {
58
- switch (_a.label) {
59
- case 0:
60
- _a.trys.push([0, 2, , 3]);
61
- return [4 /*yield*/, this];
62
- case 1:
63
- result = _a.sent();
64
- return [2 /*return*/, [null, result]];
65
- case 2:
66
- error_1 = _a.sent();
67
- return [2 /*return*/, [error_1, undefined]];
68
- case 3: return [2 /*return*/];
69
- }
70
- });
71
- });
19
+
20
+ /**
21
+ * Extiende el prototipo de `Promise` para incluir un método
22
+ * que maneja errores de promesas y devuelve una tupla `[error, result]`.
23
+ *
24
+ * @returns {Promise<[any, any]>} Una promesa que se resuelve con una tupla que contiene `null` y el resultado
25
+ * si la promesa se resuelve correctamente, o el error y `undefined` si es rechazada.
26
+ */
27
+ Promise.prototype[symbolResult] = async function () {
28
+ try {
29
+ const result = await this;
30
+ return [null, result];
31
+ } catch (error) {
32
+ return [error, undefined];
33
+ }
72
34
  };
35
+
73
36
  /**
74
- * Fetches a URL and handles both network errors and JSON parsing errors.
37
+ * Realiza una solicitud HTTP utilizando `fetch` y maneja tanto los errores de red como los de parseo JSON.
75
38
  *
76
- * @template T - The expected data type of the parsed JSON response.
77
- * @param {string} url - The URL to fetch.
78
- * @param {RequestInit} [options={}] - Optional configuration for the fetch request.
79
- * @returns {Promise<[any, T | undefined]>} A promise that resolves with a tuple containing either the error and `undefined` if something went wrong, or `null` and the parsed JSON data if successful.
39
+ * @param {string} url - La URL a la que se hará la solicitud.
40
+ * @param {RequestInit} [options={}] - Opciones opcionales para configurar la solicitud `fetch`.
41
+ * @returns {Promise<[any, any]>} Una promesa que se resuelve con una tupla que contiene el error y `undefined` si ocurre un error,
42
+ * o `null` y los datos parseados si la solicitud y el parseo del JSON son exitosos.
80
43
  */
81
- function useFetchError(url_1) {
82
- return __awaiter(this, arguments, void 0, function (url, options) {
83
- var _a, error, response, _b, parseError, data;
84
- if (options === void 0) { options = {}; }
85
- return __generator(this, function (_c) {
86
- switch (_c.label) {
87
- case 0: return [4 /*yield*/, fetch(url, options)[symbol]()];
88
- case 1:
89
- _a = _c.sent(), error = _a[0], response = _a[1];
90
- if (error) {
91
- return [2 /*return*/, [error, undefined]]; // Retorna el error si ocurrió
92
- }
93
- return [4 /*yield*/, response.json()[symbol]()];
94
- case 2:
95
- _b = _c.sent(), parseError = _b[0], data = _b[1];
96
- if (parseError) {
97
- return [2 /*return*/, [parseError, undefined]]; // Retorna el error al parsear el JSON
98
- }
99
- return [2 /*return*/, [null, data]]; // Retorna el resultado si todo fue bien
100
- }
101
- });
102
- });
44
+ async function useFetchError(url, options = {}) {
45
+ const [error, response] = await fetch(url, options)[symbolResult]();
46
+
47
+ if (error) {
48
+ return [error, undefined]; // Retorna el error si ocurrió
49
+ }
50
+
51
+ const [parseError, data] = await response.json()[symbolResult]();
52
+
53
+ if (parseError) {
54
+ return [parseError, undefined]; // Retorna el error al parsear el JSON
55
+ }
56
+
57
+ return [null, data]; // Retorna el resultado si todo fue bien
103
58
  }