use-fetch-error 1.0.0 → 1.0.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/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.2",
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
+ * Extends the `Function` prototype to include a method
5
+ * that handles errors and returns a tuple `[error, result]`.
6
+ *
7
+ * @param {...any[]} args - The arguments to be passed to the function.
8
+ * @returns {[any, any]} A tuple with `null` and the result if the function executes successfully,
9
+ * or the error and `undefined` if an exception occurs.
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
+ * Extends the `Promise` prototype to include a method
22
+ * that handles promise errors and returns a tuple `[error, result]`.
23
+ *
24
+ * @returns {Promise<[any, any]>} A promise that resolves with a tuple containing `null` and the result
25
+ * if the promise resolves successfully, or the error and `undefined` if it is rejected.
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
+ * Makes an HTTP request using `fetch` and handles both network errors and JSON parsing errors.
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 - The URL to which the request will be made.
40
+ * @param {RequestInit} [options={}] - Optional options to configure the `fetch` request.
41
+ * @returns {Promise<[any, any]>} A promise that resolves with a tuple containing the error and `undefined` if an error occurs,
42
+ * or `null` and the parsed data if the request and JSON parsing are successful.
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]; // Returns the error if one occurred
49
+ }
50
+
51
+ const [parseError, data] = await response.json()[symbolResult]();
52
+
53
+ if (parseError) {
54
+ return [parseError, undefined]; // Returns the error when parsing JSON
55
+ }
56
+
57
+ return [null, data]; // Returns the result if everything went well
103
58
  }
package/index.js DELETED
@@ -1,35 +0,0 @@
1
- const symbolResult = Symbol("result");
2
-
3
- Function.prototype[symbolResult] = function (...args) {
4
- try {
5
- const result = this.apply(this, args);
6
- return [null, result];
7
- } catch (error) {
8
- return [error, undefined];
9
- }
10
- };
11
-
12
- Promise.prototype[symbolResult] = async function () {
13
- try {
14
- const result = await this;
15
- return [null, result];
16
- } catch (error) {
17
- return [error, undefined];
18
- }
19
- };
20
-
21
- async function useFetch(url, options = {}) {
22
- const [error, response] = await fetch(url, options)[symbolResult]();
23
-
24
- if (error) {
25
- return [error, undefined]; // Retorna el error si ocurrió
26
- }
27
-
28
- const [parseError, data] = await response.json()[symbolResult]();
29
-
30
- if (parseError) {
31
- return [parseError, undefined]; // Retorna el error al parsear el JSON
32
- }
33
-
34
- return [null, data]; // Retorna el resultado si todo fue bien
35
- }