safe-wrapper 1.0.7 → 2.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.
package/2.0.0 ADDED
File without changes
package/README.md CHANGED
@@ -1,107 +1,141 @@
1
1
  ## safe-wrapper
2
2
 
3
- safe-wrapper is a lightweight utility for javascript that simplifies error handling for both synchronous and asynchronous functions. inspired by the [safe assignment operator proposal](https://github.com/arthurfiorette/proposal-safe-assignment-operator), this utility allows for graceful error management by returning a tuple of the result and error, making it easy to handle various error types.
3
+ [![npm version](https://img.shields.io/npm/v/safe-wrapper.svg)](https://www.npmjs.com/package/safe-wrapper)
4
+ [![License](https://img.shields.io/npm/l/safe-wrapper.svg)](https://github.com/mcking-07/safe-wrapper/blob/main/LICENSE)
5
+ [![Build Status](https://github.com/mcking-07/safe-wrapper/workflows/publish/badge.svg)](https://github.com/mcking-07/safe-wrapper/actions)
6
+ [![npm downloads](https://img.shields.io/npm/dm/safe-wrapper.svg)](https://www.npmjs.com/package/safe-wrapper)
4
7
 
5
- #### Installation
8
+ safe-wrapper is a lightweight utility for javascript that simplifies error handling for both synchronous and asynchronous functions. inspired by the [safe assignment operator proposal](https://github.com/arthurfiorette/proposal-safe-assignment-operator), this utility allows for graceful error management by wrapping functions in a way that enables error handling without the need for explicit `try-catch` blocks.
6
9
 
7
- ```
10
+ ### Features
11
+
12
+ - handles synchronous and asynchronous functions.
13
+ - supports specifying error types to control which errors are caught and handled.
14
+ - returns consistent responses in `[error, result]` format where error is null if no error occurred.
15
+ - supports custom error transformation for advanced error handling.
16
+
17
+ ### Installation
18
+
19
+ ```sh
8
20
  npm install safe-wrapper
9
21
  ```
10
22
 
11
- #### Usage
23
+ ### Usage
12
24
 
13
- import `safe` from `safe-wrapper` to use it with any function. it takes the result of a function as its first argument and an optional array of `error types` to catch as the second argument. the function returns an array `[error, result]`, where `error` is an instance of the specified error type or `null` if successful, and `result` is the result of the function when there is no error.
25
+ import `safe` from `safe-wrapper` to use it with any function.
14
26
 
15
- #### synchronous example
27
+ the `safe` function takes a target function (synchronous or asynchronous) and returns a function which handles errors and returns a response in a consistent way. the function returns an array `[error, result]`, where `error` is an instance of the specified error type or `null` if successful, and `result` is the result of the function when there is no error.
16
28
 
17
- in this example, we handle a synchronous function that may return an error.
29
+ #### directly wrapping functions
30
+
31
+ we can directly wrap any function definition with safe.
18
32
 
19
33
  ```javascript
20
34
  import { safe } from 'safe-wrapper';
21
35
 
22
- const sync = () => {
23
- return new Error('sync error occurred');
24
- }
25
-
26
- const [error, result] = safe(sync());
36
+ const safeSync = safe((args) => {
37
+ throw new Error('sync error occurred');
38
+ });
27
39
 
28
- if (error) {
29
- return handle(error);
30
- }
40
+ const safeAsync = safe(async (args) => {
41
+ throw new Error('async error occurred');
42
+ });
31
43
 
32
- return handle(result);
44
+ const [error, result] = await safeAsync(args);
33
45
  ```
34
46
 
35
- #### synchronous example with error type check
47
+ #### wrapping existing functions
36
48
 
37
- we can specify error types to catch specific errors. if an unknown error type occurs, it will be thrown instead.
49
+ safe can be applied to pre-existing functions, including ones from third-party libraries.
38
50
 
39
51
  ```javascript
40
52
  import { safe } from 'safe-wrapper';
41
53
 
42
- const sync = () => {
43
- return new TypeError('sync type error occurred');
44
- }
45
-
46
- const [error, result] = safe(sync(), [TypeError]);
47
-
48
- if (error) {
49
- return handle(error);
54
+ const sync = (args) => {
55
+ throw new Error('sync error occurred');
50
56
  }
51
57
 
52
- return handle(result);
58
+ const safeSync = safe(sync);
59
+ const [error, result] = safeSync(args);
53
60
  ```
54
61
 
55
- #### asynchronous example
62
+ #### handling specific error types
56
63
 
57
- in this example, we handle a synchronous function that may throw an error.
64
+ we can specify error types to catch, allowing other errors to throw.
58
65
 
59
66
  ```javascript
60
67
  import { safe } from 'safe-wrapper';
61
68
 
62
- const async = () => {
63
- throw new Error('async error occurred');
64
- }
69
+ const safeAsync = safe(async (args) => {
70
+ throw new TypeError('async type error occurred');
71
+ }, [TypeError]);
65
72
 
66
- const [error, result] = await safe(async());
73
+ const [error, result] = await safeAsync(args);
74
+ ```
67
75
 
68
- if (error) {
69
- return handle(error);
76
+ #### handling multiple error types
77
+
78
+ we can specify multiple error types when wrapping a function, enabling safe to catch any of the specified errors.
79
+
80
+ ```javascript
81
+ import { safe } from 'safe-wrapper';
82
+
83
+ const sync = (args) => {
84
+ if (args) {
85
+ throw new TypeError('sync type error occurred');
86
+ } else {
87
+ throw new RangeError('sync range error occurred');
88
+ }
70
89
  }
71
90
 
72
- return handle(result);
91
+ const safeSync = safe(sync, [TypeError, RangeError]);
92
+ const [error, result] = safeSync(args);
73
93
  ```
74
94
 
75
- #### asynchronous example with error type check
95
+ #### using custom error transformer
76
96
 
77
- we can specify error types with asynchronous functions as well.
97
+ you can provide a custom error transformer function to modify how errors are handled:
78
98
 
79
99
  ```javascript
80
100
  import { safe } from 'safe-wrapper';
81
101
 
82
- const async = () => {
83
- throw new TypeError('async type error occurred');
84
- }
102
+ const transformer = (error) => ({
103
+ code: error.name,
104
+ message: error.message,
105
+ timestamp: new Date()
106
+ });
85
107
 
86
- const [error, result] = await safe(async(), [TypeError]);
108
+ const safeWithTransform = safe(
109
+ () => { throw new Error('custom error'); },
110
+ [Error],
111
+ transformer
112
+ );
87
113
 
88
- if (error) {
89
- return handle(error);
90
- }
114
+ const [error, result] = safeWithTransform();
115
+ // error will be: { code: 'Error', message: 'custom error', timestamp: Date }
116
+ ```
117
+
118
+ #### wrapping built-in functions
119
+
120
+ we can also wrap built-in functions, like `JSON.parse`, `Object.keys`, and more.
121
+
122
+ ```javascript
123
+ import { safe } from 'safe-wrapper';
124
+
125
+ const safeJsonParse = safe(JSON.parse);
126
+ const [error, result] = safeJsonParse('invalid_json');
91
127
 
92
- return handle(result);
128
+ const [error, result] = safe(Object.keys, [TypeError])(null);
93
129
  ```
94
130
 
95
- #### Important Notes
96
- - async operations: should throw errors when they fail.
97
- - sync operations: should return errors instead of throwing them.
131
+ ### API Reference
98
132
 
99
- #### API
133
+ `safe(action, types, transformer)`
100
134
 
101
- ```safe(response, types)```
102
135
  - parameters
103
- - response (any): result of the function call, either synchronous or asynchronous.
104
- - types (array, optional): an array of error types to catch specifically. if an error does not match any of these types, it will be thrown.
136
+ - action (function): function to be wrapped. it can either be synchronous or asynchronous.
137
+ - types (array, optional): an array of error types to catch. if no types are specified, all errors are caught. each element must be a valid error constructor.
138
+ - transformer (function, optional): a function that takes an error object and returns a transformed version of it. if not provided, the original error is used.
105
139
  - returns `[error, result]`
106
- - error (error | null): the error caught from the function, if any.
107
- - result (any): the result of the function, if no error occurs.
140
+ - error (error | null): the error object if error occurred, otherwise null. if an transformer is provided, this will be the transformed error.
141
+ - result (any): the result of the action function if no error occurred, otherwise null.
package/lib/index.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";var c=Object.defineProperty;var a=Object.getOwnPropertyDescriptor;var h=Object.getOwnPropertyNames;var o=Object.prototype.hasOwnProperty;var r=(n,t)=>{for(var u in t)c(n,u,{get:t[u],enumerable:!0})},g=(n,t,u,f)=>{if(t&&typeof t=="object"||typeof t=="function")for(let l of h(t))!o.call(n,l)&&l!==u&&c(n,l,{get:()=>t[l],enumerable:!(f=a(t,l))||f.enumerable});return n};var m=n=>g(c({},"__esModule",{value:!0}),n);var w={};r(w,{safe:()=>e});module.exports=m(w);var i=(n,t=[])=>{if(!t.length)return[n,null];if(t.some(u=>n instanceof u))return[n,null];throw n},e=(n,t=[])=>n instanceof Promise?n.then(u=>[null,u]).catch(u=>i(u,t)):n instanceof Error?i(n,t):[null,n];
1
+ "use strict";var s=Object.defineProperty;var i=Object.getOwnPropertyDescriptor;var a=Object.getOwnPropertyNames;var l=Object.prototype.hasOwnProperty;var h=(e,n)=>{for(var t in n)s(e,t,{get:n[t],enumerable:!0})},d=(e,n,t,r)=>{if(n&&typeof n=="object"||typeof n=="function")for(let c of a(n))!l.call(e,c)&&c!==t&&s(e,c,{get:()=>n[c],enumerable:!(r=i(n,c))||r.enumerable});return e};var m=e=>d(s({},"__esModule",{value:!0}),e);var P={};h(P,{safe:()=>g});module.exports=m(P);var o=({error:e=null,data:n=null,result:t=null})=>[e,t||n],b=e=>(...n)=>{try{let t=e(...n);return t instanceof Promise?t.then(r=>o({error:r})).catch(r=>o({error:r})):o({error:t})}catch(t){return o({error:t})}},f=(e,n=[],t=void 0)=>{let r=!n.length||n.some(u=>e instanceof u),c=t!==void 0&&typeof t=="function";if(r)return c?b(t)(e):o({error:e});throw e},g=(e,n=[],t=void 0)=>(...r)=>{try{let c=e(...r);return c instanceof Promise?c.then(u=>o({data:u})).catch(u=>f(u,n,t)):o({result:c})}catch(c){return f(c,n,t)}};
package/lib/index.d.ts CHANGED
@@ -1,8 +1,9 @@
1
1
  /**
2
- * safely executes the result of a function or a promise and handles any errors that occur.
2
+ * safely executes a synchronous or asynchronous action, handles any errors that occur and returns the result in a consistent response structure.
3
3
  *
4
- * @param {any} response - the result of a synchronous or asynchronous function, or a promise to execute.
5
- * @param {Array<ErrorConstructor>} [types=[]] - an optional array of error classes to check against.
6
- * @returns {Promise<[null, any]|[Error, null]>|[null, any]|[Error, null]} - returns an array where the first element is null if successful, or an error if it fails. if the input is a promise, it resolves to that array; otherwise, it returns the array directly.
4
+ * @param {Function} action - the function to be wrapped, which can either be synchronous or asynchronous.
5
+ * @param {Array<ErrorConstructor>} [types = []] - an optional array of error types to check against.
6
+ * @param {Function} [transformer = undefined] - an optional function to transform the error object.
7
+ * @returns {Promise<[Error, null] | [null, any]> | [Error, null] | [null, any]} - a tuple where the first element is null, if the execution was successful, or an error object if an error occurred. the second element is the result of the action, if available.
7
8
  */
8
- export function safe(response: any, types?: ErrorConstructor[] | undefined): Promise<[null, any] | [Error, null]> | [null, any] | [Error, null];
9
+ export function safe(action: Function, types?: Array<ErrorConstructor>, transformer?: Function): Promise<[Error, null] | [null, any]> | [Error, null] | [null, any];
package/lib/index.mjs CHANGED
@@ -1 +1 @@
1
- var l=(n,t=[])=>{if(!t.length)return[n,null];if(t.some(u=>n instanceof u))return[n,null];throw n},c=(n,t=[])=>n instanceof Promise?n.then(u=>[null,u]).catch(u=>l(u,t)):n instanceof Error?l(n,t):[null,n];export{c as safe};
1
+ var o=({error:t=null,data:e=null,result:n=null})=>[t,n||e],f=t=>(...e)=>{try{let n=t(...e);return n instanceof Promise?n.then(c=>o({error:c})).catch(c=>o({error:c})):o({error:n})}catch(n){return o({error:n})}},s=(t,e=[],n=void 0)=>{let c=!e.length||e.some(u=>t instanceof u),r=n!==void 0&&typeof n=="function";if(c)return r?f(n)(t):o({error:t});throw t},i=(t,e=[],n=void 0)=>(...c)=>{try{let r=t(...c);return r instanceof Promise?r.then(u=>o({data:u})).catch(u=>s(u,e,n)):o({result:r})}catch(r){return s(r,e,n)}};export{i as safe};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "safe-wrapper",
3
- "version": "1.0.7",
3
+ "version": "2.0.1",
4
4
  "description": "a js-util for safely wrapping synchronous and asynchronous functions to handle errors based on specified types.",
5
5
  "type": "module",
6
6
  "main": "lib/index.cjs",
@@ -40,4 +40,4 @@
40
40
  "esbuild": "^0.24.0",
41
41
  "typescript": "^5.6.3"
42
42
  }
43
- }
43
+ }