promise-tuple 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/LICENSE ADDED
@@ -0,0 +1,15 @@
1
+ ISC License
2
+
3
+ Copyright (c) 2024 Eduardo DONATO
4
+
5
+ Permission to use, copy, modify, and/or distribute this software for any
6
+ purpose with or without fee is hereby granted, provided that the above
7
+ copyright notice and this permission notice appear in all copies.
8
+
9
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
10
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
11
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
12
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
13
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
14
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
15
+ PERFORMANCE OF THIS SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,191 @@
1
+ # Promise Tuple
2
+
3
+ A lightweight utility function for handling promises with Go-like error handling pattern. Instead of using try/catch blocks, `promiseTuple` returns a tuple containing either an error or a result.
4
+
5
+ ## Features
6
+
7
+ - 🎯 Simple and intuitive error handling
8
+ - 📦 TypeScript support with full type safety
9
+ - 🔄 Go-style error handling pattern
10
+ - ⚡ Zero dependencies
11
+ - 🌐 Works in Node.js and browsers
12
+
13
+ ## Installation
14
+
15
+ ```bash
16
+ npm install promise-tuple
17
+ ```
18
+
19
+ or with yarn:
20
+
21
+ ```bash
22
+ yarn add promise-tuple
23
+ ```
24
+
25
+ or with pnpm:
26
+
27
+ ```bash
28
+ pnpm add promise-tuple
29
+ ```
30
+
31
+ ## How to Use
32
+
33
+ ### Import
34
+
35
+ **ES Module:**
36
+
37
+ ```typescript
38
+ import promiseTuple from 'promise-tuple';
39
+ ```
40
+
41
+ **CommonJS:**
42
+
43
+ ```javascript
44
+ const promiseTuple = require('promise-tuple');
45
+ ```
46
+
47
+ ### Basic Usage
48
+
49
+ ```typescript
50
+ import promiseTuple from 'promise-tuple';
51
+
52
+ // Example with a fetch request
53
+ const [error, data] = await promiseTuple(fetch('/api/data'));
54
+
55
+ if (error) {
56
+ console.error('Error:', error);
57
+ } else {
58
+ console.log('Data:', data);
59
+ }
60
+ ```
61
+
62
+ ### With Custom Types
63
+
64
+ You can specify the type of the resolved value and error:
65
+
66
+ ```typescript
67
+ import promiseTuple from 'promise-tuple';
68
+
69
+ interface User {
70
+ id: number;
71
+ name: string;
72
+ }
73
+
74
+ const [error, user] = await promiseTuple<User>(
75
+ fetch('/api/user').then(res => res.json())
76
+ );
77
+
78
+ if (error) {
79
+ console.error('Failed to fetch user:', error);
80
+ } else {
81
+ console.log('User:', user?.name);
82
+ }
83
+ ```
84
+
85
+ ### In async/await Functions
86
+
87
+ ```typescript
88
+ async function getUser(userId: string) {
89
+ const [error, response] = await promiseTuple(
90
+ fetch(`/api/users/${userId}`)
91
+ );
92
+
93
+ if (error) {
94
+ throw new Error(`Failed to fetch user: ${error}`);
95
+ }
96
+
97
+ const [parseError, user] = await promiseTuple(
98
+ response.json()
99
+ );
100
+
101
+ if (parseError) {
102
+ throw new Error(`Failed to parse user data: ${parseError}`);
103
+ }
104
+
105
+ return user;
106
+ }
107
+ ```
108
+
109
+ ### With Custom Error Types
110
+
111
+ ```typescript
112
+ import promiseTuple from 'promise-tuple';
113
+
114
+ interface CustomError {
115
+ code: string;
116
+ message: string;
117
+ }
118
+
119
+ const [error, data] = await promiseTuple<string, CustomError>(
120
+ someAsyncOperation()
121
+ );
122
+ ```
123
+
124
+ ## API
125
+
126
+ ### `promiseTuple<R, E>(promise)`
127
+
128
+ Handles a promise and returns a tuple with error and result.
129
+
130
+ **Parameters:**
131
+
132
+ - `promise: Promise<R>` - The promise to handle
133
+
134
+ **Returns:**
135
+
136
+ - `Promise<[E | undefined, R | undefined]>` - A promise that resolves to a tuple containing either an error or a result
137
+
138
+ **Type Parameters:**
139
+
140
+ - `R` (default: `unknown`) - The type of the resolved value
141
+ - `E` (default: `unknown`) - The type of the error
142
+
143
+ **Behavior:**
144
+
145
+ - If the promise resolves: returns `[undefined, result]`
146
+ - If the promise rejects: returns `[error, undefined]`
147
+
148
+ ## Examples
149
+
150
+ ### Database Query
151
+
152
+ ```typescript
153
+ import promiseTuple from 'promise-tuple';
154
+ import db from './database';
155
+
156
+ async function getUserById(id: number) {
157
+ const [error, user] = await promiseTuple(
158
+ db.users.findById(id)
159
+ );
160
+
161
+ if (error) {
162
+ return { success: false, message: 'User not found' };
163
+ }
164
+
165
+ return { success: true, user };
166
+ }
167
+ ```
168
+
169
+ ### File Operations
170
+
171
+ ```typescript
172
+ import promiseTuple from 'promise-tuple';
173
+ import fs from 'fs/promises';
174
+
175
+ async function readConfigFile(path: string) {
176
+ const [error, content] = await promiseTuple(
177
+ fs.readFile(path, 'utf-8')
178
+ );
179
+
180
+ if (error) {
181
+ console.error('Failed to read config:', error);
182
+ return null;
183
+ }
184
+
185
+ return JSON.parse(content);
186
+ }
187
+ ```
188
+
189
+ ## License
190
+
191
+ ISC
package/dist/index.cjs ADDED
@@ -0,0 +1,35 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ default: () => index_default,
24
+ promiseTuple: () => promiseTuple
25
+ });
26
+ module.exports = __toCommonJS(index_exports);
27
+ async function promiseTuple(promise) {
28
+ return promise.then((result) => [void 0, result]).catch((error) => [error, void 0]);
29
+ }
30
+ var index_default = promiseTuple;
31
+ // Annotate the CommonJS export names for ESM import in node:
32
+ 0 && (module.exports = {
33
+ promiseTuple
34
+ });
35
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../index.ts"],"sourcesContent":["/**\r\n * Handles a promise and returns a tuple with error and result.\r\n *\r\n * This function wraps a promise and returns a tuple containing either an error or a result,\r\n * similar to Go's error handling pattern. If the promise resolves, the tuple will contain\r\n * `[undefined, result]`. If the promise rejects, the tuple will contain `[error, undefined]`.\r\n *\r\n * @template R - The type of the resolved value. Defaults to `unknown`.\r\n * @template E - The type of the error. Defaults to `unknown`.\r\n * @param promise - The promise to handle.\r\n * @returns A promise that resolves to a tuple containing either an error or a result.\r\n *\r\n * @example\r\n * const [error, data] = await promiseTuple(fetchData());\r\n * if (error) {\r\n * console.error('Error:', error);\r\n * } else {\r\n * console.log('Data:', data);\r\n * }\r\n */\r\nexport async function promiseTuple<R = unknown, E = unknown>(\r\n promise: Promise<R>\r\n): Promise<[E | undefined, R | undefined]> {\r\n return promise\r\n .then((result) => [undefined, result] as [undefined, R])\r\n .catch((error) => [error, undefined] as [E, undefined])\r\n}\r\nexport default promiseTuple\r\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAoBA,eAAsB,aAClB,SACuC;AACvC,SAAO,QACF,KAAK,CAAC,WAAW,CAAC,QAAW,MAAM,CAAmB,EACtD,MAAM,CAAC,UAAU,CAAC,OAAO,MAAS,CAAmB;AAC9D;AACA,IAAO,gBAAQ;","names":[]}
@@ -0,0 +1,23 @@
1
+ /**
2
+ * Handles a promise and returns a tuple with error and result.
3
+ *
4
+ * This function wraps a promise and returns a tuple containing either an error or a result,
5
+ * similar to Go's error handling pattern. If the promise resolves, the tuple will contain
6
+ * `[undefined, result]`. If the promise rejects, the tuple will contain `[error, undefined]`.
7
+ *
8
+ * @template R - The type of the resolved value. Defaults to `unknown`.
9
+ * @template E - The type of the error. Defaults to `unknown`.
10
+ * @param promise - The promise to handle.
11
+ * @returns A promise that resolves to a tuple containing either an error or a result.
12
+ *
13
+ * @example
14
+ * const [error, data] = await promiseTuple(fetchData());
15
+ * if (error) {
16
+ * console.error('Error:', error);
17
+ * } else {
18
+ * console.log('Data:', data);
19
+ * }
20
+ */
21
+ declare function promiseTuple<R = unknown, E = unknown>(promise: Promise<R>): Promise<[E | undefined, R | undefined]>;
22
+
23
+ export { promiseTuple as default, promiseTuple };
@@ -0,0 +1,23 @@
1
+ /**
2
+ * Handles a promise and returns a tuple with error and result.
3
+ *
4
+ * This function wraps a promise and returns a tuple containing either an error or a result,
5
+ * similar to Go's error handling pattern. If the promise resolves, the tuple will contain
6
+ * `[undefined, result]`. If the promise rejects, the tuple will contain `[error, undefined]`.
7
+ *
8
+ * @template R - The type of the resolved value. Defaults to `unknown`.
9
+ * @template E - The type of the error. Defaults to `unknown`.
10
+ * @param promise - The promise to handle.
11
+ * @returns A promise that resolves to a tuple containing either an error or a result.
12
+ *
13
+ * @example
14
+ * const [error, data] = await promiseTuple(fetchData());
15
+ * if (error) {
16
+ * console.error('Error:', error);
17
+ * } else {
18
+ * console.log('Data:', data);
19
+ * }
20
+ */
21
+ declare function promiseTuple<R = unknown, E = unknown>(promise: Promise<R>): Promise<[E | undefined, R | undefined]>;
22
+
23
+ export { promiseTuple as default, promiseTuple };
package/dist/index.js ADDED
@@ -0,0 +1,10 @@
1
+ // index.ts
2
+ async function promiseTuple(promise) {
3
+ return promise.then((result) => [void 0, result]).catch((error) => [error, void 0]);
4
+ }
5
+ var index_default = promiseTuple;
6
+ export {
7
+ index_default as default,
8
+ promiseTuple
9
+ };
10
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../index.ts"],"sourcesContent":["/**\r\n * Handles a promise and returns a tuple with error and result.\r\n *\r\n * This function wraps a promise and returns a tuple containing either an error or a result,\r\n * similar to Go's error handling pattern. If the promise resolves, the tuple will contain\r\n * `[undefined, result]`. If the promise rejects, the tuple will contain `[error, undefined]`.\r\n *\r\n * @template R - The type of the resolved value. Defaults to `unknown`.\r\n * @template E - The type of the error. Defaults to `unknown`.\r\n * @param promise - The promise to handle.\r\n * @returns A promise that resolves to a tuple containing either an error or a result.\r\n *\r\n * @example\r\n * const [error, data] = await promiseTuple(fetchData());\r\n * if (error) {\r\n * console.error('Error:', error);\r\n * } else {\r\n * console.log('Data:', data);\r\n * }\r\n */\r\nexport async function promiseTuple<R = unknown, E = unknown>(\r\n promise: Promise<R>\r\n): Promise<[E | undefined, R | undefined]> {\r\n return promise\r\n .then((result) => [undefined, result] as [undefined, R])\r\n .catch((error) => [error, undefined] as [E, undefined])\r\n}\r\nexport default promiseTuple\r\n"],"mappings":";AAoBA,eAAsB,aAClB,SACuC;AACvC,SAAO,QACF,KAAK,CAAC,WAAW,CAAC,QAAW,MAAM,CAAmB,EACtD,MAAM,CAAC,UAAU,CAAC,OAAO,MAAS,CAAmB;AAC9D;AACA,IAAO,gBAAQ;","names":[]}
package/package.json ADDED
@@ -0,0 +1,63 @@
1
+ {
2
+ "name": "promise-tuple",
3
+ "version": "1.0.0",
4
+ "description": "A utility function for handling promises with Go-like error handling pattern",
5
+ "main": "./dist/index.cjs",
6
+ "module": "./dist/index.js",
7
+ "types": "./dist/index.d.ts",
8
+ "type": "module",
9
+ "exports": {
10
+ ".": {
11
+ "types": "./dist/index.d.ts",
12
+ "require": {
13
+ "types": "./dist/index.d.cts",
14
+ "default": "./dist/index.cjs"
15
+ },
16
+ "import": {
17
+ "types": "./dist/index.d.ts",
18
+ "default": "./dist/index.js"
19
+ }
20
+ }
21
+ },
22
+ "sideEffects": false,
23
+ "scripts": {
24
+ "clean": "node -e \"require('fs').rmSync('dist', { recursive: true, force: true })\"",
25
+ "build": "tsup index.ts",
26
+ "test": "tsx index.test.ts",
27
+ "prepublishOnly": "npm run clean && npm run build && npm test"
28
+ },
29
+ "keywords": [
30
+ "promise",
31
+ "error-handling",
32
+ "async",
33
+ "utility",
34
+ "go-style",
35
+ "tuple",
36
+ "await",
37
+ "typescript"
38
+ ],
39
+ "author": "Eduardo DONATO <eduardo.donato@gmail.com>",
40
+ "license": "ISC",
41
+ "repository": {
42
+ "type": "git",
43
+ "url": "git+https://github.com/ebdonato/promise-tuple.git"
44
+ },
45
+ "bugs": {
46
+ "url": "https://github.com/ebdonato/promise-tuple/issues"
47
+ },
48
+ "homepage": "https://github.com/ebdonato/promise-tuple#readme",
49
+ "engines": {
50
+ "node": ">=16"
51
+ },
52
+ "files": [
53
+ "dist",
54
+ "README.md",
55
+ "LICENSE"
56
+ ],
57
+ "devDependencies": {
58
+ "@types/node": "^20.0.0",
59
+ "tsup": "^8.5.1",
60
+ "tsx": "^4.21.0",
61
+ "typescript": "^5.9.3"
62
+ }
63
+ }