use-fetch-error 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/index.js ADDED
@@ -0,0 +1,35 @@
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
+ }
package/package.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "name": "use-fetch-error",
3
+ "version": "1.0.0",
4
+ "main": "src/index.js",
5
+ "browser": "src/index.js"
6
+ }
package/src/index.js ADDED
@@ -0,0 +1,103 @@
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
+ }
53
+ };
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
+ });
72
+ };
73
+ /**
74
+ * Fetches a URL and handles both network errors and JSON parsing errors.
75
+ *
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.
80
+ */
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
+ });
103
+ }
package/src/index.ts ADDED
@@ -0,0 +1,80 @@
1
+ const symbol = Symbol("result");
2
+
3
+ /**
4
+ * Interface that extends the native `Function` prototype
5
+ * to include a method that handles errors and returns a tuple
6
+ * containing the error and result.
7
+ */
8
+ interface FunctionWithSymbol extends Function {
9
+ /**
10
+ * Executes the function and returns a tuple `[error, result]`.
11
+ * @param {...any[]} args - Arguments to pass to the function.
12
+ * @returns {[any, any]} A tuple containing `null` and the result if successful, or the error and `undefined` if it throws.
13
+ */
14
+ [symbol](...args: any[]): [any, any];
15
+ }
16
+
17
+ Function.prototype[symbol] = function (
18
+ this: FunctionWithSymbol,
19
+ ...args: any[]
20
+ ): [any, any] {
21
+ try {
22
+ const result = this.apply(this, args);
23
+ return [null, result];
24
+ } catch (error) {
25
+ return [error, undefined];
26
+ }
27
+ };
28
+
29
+ /**
30
+ * Interface that extends the native `Promise` prototype
31
+ * to include a method that handles promise rejections and
32
+ * resolves to a tuple `[error, result]`.
33
+ *
34
+ * @template T - The type of the resolved value of the promise.
35
+ */
36
+ interface PromiseWithSymbol<T> extends Promise<T> {
37
+ /**
38
+ * Resolves the promise and returns a tuple `[error, result]`.
39
+ * @returns {Promise<[any, T | undefined]>} A promise that resolves with a tuple containing `null` and the result if successful, or the error and `undefined` if rejected.
40
+ */
41
+ [symbol](): Promise<[any, T | undefined]>;
42
+ }
43
+
44
+ Promise.prototype[symbol] = async function <T>(
45
+ this: PromiseWithSymbol<T>
46
+ ): Promise<[any, T | undefined]> {
47
+ try {
48
+ const result = await this;
49
+ return [null, result];
50
+ } catch (error) {
51
+ return [error, undefined];
52
+ }
53
+ };
54
+
55
+ /**
56
+ * Fetches a URL and handles both network errors and JSON parsing errors.
57
+ *
58
+ * @template T - The expected data type of the parsed JSON response.
59
+ * @param {string} url - The URL to fetch.
60
+ * @param {RequestInit} [options={}] - Optional configuration for the fetch request.
61
+ * @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.
62
+ */
63
+ export async function useFetchError<T>(
64
+ url: string,
65
+ options: RequestInit = {}
66
+ ): Promise<[any, T | undefined]> {
67
+ const [error, response] = await fetch(url, options)[symbol]();
68
+
69
+ if (error) {
70
+ return [error, undefined]; // Retorna el error si ocurrió
71
+ }
72
+
73
+ const [parseError, data] = await (response as Response).json()[symbol]();
74
+
75
+ if (parseError) {
76
+ return [parseError, undefined]; // Retorna el error al parsear el JSON
77
+ }
78
+
79
+ return [null, data]; // Retorna el resultado si todo fue bien
80
+ }