go-go-try 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,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2022 Alisson Cavalcante Agiani thelinuxlich@gmail.com https://astoilkov.com
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,70 @@
1
+ # `go-go-try`
2
+
3
+ > Tries to execute a sync/async function, returns a specified default value if the function throws.
4
+
5
+ [![Gzipped Size](https://img.shields.io/bundlephobia/minzip/good-try)](https://bundlephobia.com/result?p=good-try)
6
+ [![Build Status](https://img.shields.io/github/workflow/status/astoilkov/good-try/CI)](https://github.com/astoilkov/good-try/actions/workflows/main.yml)
7
+
8
+ ## Why
9
+
10
+ Why not [`nice-try`](https://github.com/electerious/nice-try) with it's 70+ million downloads per month?
11
+
12
+ - `go-go-try` supports async functions.
13
+ - `go-go-try` supports an optional default value.
14
+ - `go-go-try` allows you to capture the thrown error.
15
+ - `go-go-try` is written in TypeScript. The types are written in a way that reduce developer errors.
16
+ - `go-go-try` is inspired by Golang error catching.
17
+
18
+ Why not just `try`/`catch`?
19
+
20
+ - In a lot of cases, `try`/`catch` is still the better option.
21
+ - Nested `try`/`catch` statements are hard to process mentally. They also indent the code and make it hard to read. A single `try`/`catch` does the same but to a lesser degree.
22
+ - If you [prefer const](https://eslint.org/docs/latest/rules/prefer-const), `try`/`catch` statements get in the way because you need to use `let` if you need the variable outside of the `try`/`catch` scope:
23
+ ```ts
24
+ let todos
25
+ try {
26
+ todos = JSON.parse(localStorage.getItem('todos'))
27
+ } catch {}
28
+ return todos.filter((todo) => todo.done)
29
+ ```
30
+ - It takes more space. It's slower to type.
31
+
32
+ ## Install
33
+
34
+ ```bash
35
+ npm install go-go-try
36
+ ```
37
+
38
+ ## Usage
39
+
40
+ ```ts
41
+ import goTry from 'go-go-try'
42
+
43
+ // tries to parse todos, returns empty array if it fails
44
+ const [_, value] = goTry(() => JSON.parse(todos), [])
45
+
46
+ // fetch todos, on error, fallback to empty array
47
+ const [_, todos] = await goTry(fetchTodos(), [])
48
+
49
+ // fetch todos, fallback to empty array, send error to your error tracking service
50
+ const [err, todos] = await goTry(fetchTodos(), [])
51
+ sentToErrorTrackingService(err)
52
+ ```
53
+
54
+ ## API
55
+
56
+ **First parameter** accepts:
57
+
58
+ - synchronous function `goTry(() => JSON.parse(value))`
59
+ - asynchronous function / Promise
60
+
61
+ **Second parameter** accepts:
62
+
63
+ - a value of the same type of the first parameter that will be returned if the first parameter throws
64
+
65
+ **Returns** a tuple with the possible error and result (Golang style)
66
+ If you use TypeScript, the types are well defined and won't let you make a mistake.
67
+
68
+ ## Inspiration
69
+
70
+ - This library started as a fork of [good-try](https://github.com/astoilkov/good-try) but diverged a lot so I decided to rename it
package/index.d.ts ADDED
@@ -0,0 +1,4 @@
1
+ declare type ResultTuple<T> = [string?, T?];
2
+ export default function goTry<T>(value: Promise<T>, defaultValue?: T): Promise<ResultTuple<T>>;
3
+ export default function goTry<T>(value: () => T, defaultValue?: T): ResultTuple<T>;
4
+ export {};
package/index.js ADDED
@@ -0,0 +1,37 @@
1
+ import pIsPromise from 'p-is-promise';
2
+ function isErrorWithMessage(error) {
3
+ return (typeof error === 'object' &&
4
+ error !== null &&
5
+ 'message' in error &&
6
+ typeof error.message === 'string');
7
+ }
8
+ function toErrorWithMessage(maybeError) {
9
+ if (isErrorWithMessage(maybeError)) {
10
+ return maybeError;
11
+ }
12
+ try {
13
+ return new Error(JSON.stringify(maybeError));
14
+ }
15
+ catch {
16
+ // fallback in case there's an error stringifying the maybeError
17
+ // like with circular references for example.
18
+ return new Error(String(maybeError));
19
+ }
20
+ }
21
+ function getErrorMessage(error) {
22
+ return toErrorWithMessage(error).message;
23
+ }
24
+ export default function goTry(value, defaultValue) {
25
+ try {
26
+ const unwrappedValue = typeof value === 'function' ? value() : value;
27
+ if (pIsPromise(unwrappedValue)) {
28
+ return Promise.resolve(unwrappedValue)
29
+ .then((value) => [undefined, value])
30
+ .catch((err) => [getErrorMessage(err), defaultValue]);
31
+ }
32
+ return [undefined, unwrappedValue];
33
+ }
34
+ catch (err) {
35
+ return [getErrorMessage(err), defaultValue];
36
+ }
37
+ }
package/package.json ADDED
@@ -0,0 +1,61 @@
1
+ {
2
+ "name": "go-go-try",
3
+ "version": "1.0.0",
4
+ "description": "Tries to execute a sync/async function, returns a result tuple",
5
+ "license": "MIT",
6
+ "repository": "thelinuxlich/go-go-try",
7
+ "author": {
8
+ "name": "Alisson Cavalcante Agiani",
9
+ "email": "thelinuxlich@gmail.com"
10
+ },
11
+ "type": "module",
12
+ "main": "./index.js",
13
+ "types": "./index.d.ts",
14
+ "sideEffects": false,
15
+ "engines": {
16
+ "node": ">=12"
17
+ },
18
+ "scripts": {
19
+ "build": "tsc",
20
+ "lint": "eslint --cache --format=pretty --ext=.ts ./",
21
+ "test": "yarn run build && yarn run lint && NODE_OPTIONS=--experimental-vm-modules jest --coverage --coverageReporters=text",
22
+ "release": "yarn run build && np",
23
+ "prettier": "prettier --write --config .prettierrc.yaml {*.ts,*.json}"
24
+ },
25
+ "files": [
26
+ "index.js",
27
+ "src/*.js",
28
+ "index.d.ts",
29
+ "src/*.d.ts"
30
+ ],
31
+ "keywords": [
32
+ "errors",
33
+ "try",
34
+ "catch",
35
+ "error handling",
36
+ "nice-try",
37
+ "good-try",
38
+ "go-try"
39
+ ],
40
+ "devDependencies": {
41
+ "@types/jest": "^28.1.1",
42
+ "@typescript-eslint/eslint-plugin": "^5.27.1",
43
+ "@typescript-eslint/parser": "^5.27.1",
44
+ "confusing-browser-globals": "^1.0.11",
45
+ "eslint": "^8.17.0",
46
+ "eslint-config-strictest": "^0.4.0",
47
+ "eslint-formatter-pretty": "^4.0.0",
48
+ "eslint-plugin-promise": "^6.0.0",
49
+ "eslint-plugin-unicorn": "^42.0.0",
50
+ "jest": "^28.1.1",
51
+ "jest-environment-jsdom": "^28.1.1",
52
+ "np": "^7.6.1",
53
+ "prettier": "^2.6.2",
54
+ "ts-jest": "^28.0.4",
55
+ "ts-node": "^10.8.2",
56
+ "typescript": "^4.7.3"
57
+ },
58
+ "dependencies": {
59
+ "p-is-promise": "^4.0.0"
60
+ }
61
+ }