@mkvlrn/result 5.0.0 → 5.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/README.md +14 -14
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -11,17 +11,17 @@ pnpm add @mkvlrn/result
|
|
|
11
11
|
## Usage
|
|
12
12
|
|
|
13
13
|
```typescript
|
|
14
|
-
import { Result, AsyncResult,
|
|
14
|
+
import { Result, AsyncResult, ok, err } from "@mkvlrn/result";
|
|
15
15
|
|
|
16
16
|
// Success
|
|
17
|
-
const success =
|
|
17
|
+
const success = ok(42);
|
|
18
18
|
|
|
19
19
|
// Error
|
|
20
|
-
const failure =
|
|
20
|
+
const failure = err(new Error("Something went wrong"));
|
|
21
21
|
|
|
22
22
|
// Check result
|
|
23
|
-
const result =
|
|
24
|
-
if (result.
|
|
23
|
+
const result = ok(42);
|
|
24
|
+
if (result.isError) {
|
|
25
25
|
console.log("Error:", result.error.message);
|
|
26
26
|
} else {
|
|
27
27
|
console.log("Value:", result.value);
|
|
@@ -35,13 +35,13 @@ if (result.error) {
|
|
|
35
35
|
```typescript
|
|
36
36
|
function divide(a: number, b: number): Result<number, Error> {
|
|
37
37
|
if (b === 0) {
|
|
38
|
-
return
|
|
38
|
+
return err(new Error("Division by zero"));
|
|
39
39
|
}
|
|
40
|
-
return
|
|
40
|
+
return ok(a / b);
|
|
41
41
|
}
|
|
42
42
|
|
|
43
43
|
const result = divide(10, 2);
|
|
44
|
-
if (!result.
|
|
44
|
+
if (!result.isError) {
|
|
45
45
|
console.log(result.value); // 5
|
|
46
46
|
}
|
|
47
47
|
```
|
|
@@ -53,12 +53,12 @@ async function fetchUser(id: number): AsyncResult<User, Error> {
|
|
|
53
53
|
try {
|
|
54
54
|
const response = await fetch(`/api/users/${id}`);
|
|
55
55
|
if (!response.ok) {
|
|
56
|
-
return
|
|
56
|
+
return err(new Error(`HTTP ${response.status}`));
|
|
57
57
|
}
|
|
58
58
|
const user = await response.json();
|
|
59
|
-
return
|
|
59
|
+
return ok(user);
|
|
60
60
|
} catch (error) {
|
|
61
|
-
return
|
|
61
|
+
return err(error instanceof Error ? error : new Error("Unknown error"));
|
|
62
62
|
}
|
|
63
63
|
}
|
|
64
64
|
```
|
|
@@ -78,13 +78,13 @@ class ValidationError extends Error {
|
|
|
78
78
|
|
|
79
79
|
function validateEmail(email: string): Result<string, ValidationError> {
|
|
80
80
|
if (!email.includes("@")) {
|
|
81
|
-
return
|
|
81
|
+
return err(new ValidationError(400, "custom"));
|
|
82
82
|
}
|
|
83
|
-
return
|
|
83
|
+
return ok(email);
|
|
84
84
|
}
|
|
85
85
|
|
|
86
86
|
const result = validateEmail("invalid-email");
|
|
87
|
-
if (result.
|
|
87
|
+
if (result.isError) {
|
|
88
88
|
console.log(`${result.error.customField}: ${result.error.message}`);
|
|
89
89
|
}
|
|
90
90
|
```
|