Skip to content

Commit 03eade3

Browse files
committed
BREAKING CHANGE: Implement V2
1 parent a929652 commit 03eade3

File tree

19 files changed

+2655
-1153
lines changed

19 files changed

+2655
-1153
lines changed

.github/workflows/ci.yaml

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,9 +15,7 @@ jobs:
1515

1616
runs-on: ${{ matrix.os }}
1717

18-
# Steps represent a sequence of tasks that will be executed as part of the job
1918
steps:
20-
# Checks-out your repository under $GITHUB_WORKSPACE, so your job can access it
2119
- uses: actions/checkout@v3
2220

2321
- uses: actions/setup-node@v3

LICENSE

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
The MIT License (MIT)
22

3-
Copyright © 2023 Ahmed K. A.
3+
Copyright © 2023 ahme-dev
44

55
Permission is hereby granted, free of charge, to any person obtaining a copy
66
of this software and associated documentation files (the "Software"), to deal

README.md

Lines changed: 70 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -1,81 +1,107 @@
1-
![GitHub Workflow Status](https://img.shields.io/github/actions/workflow/status/ahmeddots/tryresult/ci.yaml)
21
![NPM bundle size](https://img.shields.io/bundlephobia/min/tryresult?color=royalblue)
32
![npm](https://img.shields.io/npm/v/tryresult?label=version&color=royalblue)
43
![npm](https://img.shields.io/npm/dm/tryresult?color=gold)
54

65
# 📛 TryResult
76

8-
A typescript library to get rid of try catches, and replace them with result types, inspired by Rust and Go error handling.
7+
A tiny typescript library to get rid of try catches, and replace them with result types, inspired by Rust and Go error handling.
98

10-
![preview picture](./preview.jpg)
9+
![preview picture](./preview.png)
1110

12-
Providing simple, easier, and more elegeant error handling, TryResult gives you functions that act as wrappers and catch errors in your own functions.
13-
14-
It also currently provides functions to assert if a result has an error in it, and to use a default value in case of errors.
15-
16-
<br>
11+
Under 400 bytes and with no dependencies, TryResult only provides you with more elegant error handling and gives you functions that act as wrappers and catch errors in your own functions.
1712

1813
## Install
1914

20-
As with any npm package:
15+
As with any package, install using your favorite package manager:
2116

2217
```sh
23-
npm i tryresult
18+
pnpm i tryresult
2419
```
2520

26-
Or use Yarn:
21+
## Usage
2722

28-
```sh
29-
yarn add tryresult
30-
```
23+
The base functionality of TryResult revolves around the `Result` type, which can either be an `Ok` or an `Err`. You can create these results using the `ok` and `err` functions.
3124

32-
<br>
25+
```ts
26+
import { ok, err, Result, isOk, isErr } from "tryresult";
3327

34-
## Usage
28+
// You can create a Result with a value or an error
3529

36-
Import from the package:
30+
const success = ok("Success!"); // Result<string, Error>
31+
const failure = err(new Error("Something went wrong")); // Result<string, Error>
3732

38-
```typescript
39-
import { tryAsync, isError } from "tryresult";
33+
// You can do typesafe checks of a Result
34+
35+
if (isOk(success)) {
36+
console.log(success.value); // "Success!"
37+
}
38+
if (isErr(failure)) {
39+
console.error(failure.error); // Error: Something went wrong
40+
}
4041
```
4142

42-
Wrap your async function with `tryAsync`:
43+
### Wrapping Functions
4344

44-
```typescript
45-
let users = await tryAsync(
46-
// get a list of users from the database
47-
db.user.findMany(),
48-
);
49-
```
45+
To do away with try-catch blocks around functions you can't control, you can use wrapping functions to automatically get a `Result` type.
46+
47+
```ts
48+
import { tryFn, isErr } from "tryresult";
49+
50+
// Capture throws from async or sync functions
5051

51-
This will make the `users` variable be of type `T | Error`, meaning it can be either a value or an error (a union of types).
52+
const result = tryFn(() => {
53+
return JSON.parse('{"message": "Hello!"}');
54+
});
5255

53-
Then check for error in the variable with `isError`, and then handle the error:
56+
const asyncResult = await tryFn(async () => {
57+
const response = await fetch('https://api.example.com/data');
58+
return response.json();
59+
});
5460

55-
```typescript
56-
if (isError(users)) {
57-
return "Could not get users from db";
61+
// As shown above, the `Result` can be checked
62+
63+
if (isErr(result)) {
64+
console.error("An error occurred:", result.error); // Guaranteed to be an Error object
65+
} else {
66+
console.log(result.value.message); // "Hello!"
5867
}
68+
5969
```
6070

61-
This is a type guard and all code after the `isError` will consider result's type to be `T`.
71+
### Working with Results
6272

63-
**[v1.2.x onwards]**
73+
Several utilities are provided to make working with `Result` types easier, and abstract common functionality.
6474

65-
Let's say you're fetching something like a user's role from the db:
75+
```ts
76+
import { match, okOr, okOrThrow, mapOk, mapErr } from "tryresult";
6677

67-
```typescript
68-
const result = await tryAsync(db.user.find(id).role);
69-
```
78+
// Match on the Result type to run different logic or return different values based on whether it's Ok or Err
7079

71-
If you want to get the value and set a default value in case of error, you can use `okOr` on the result:
80+
const greeting = match(result, {
81+
ok: (value) => `Success: ${value.message}`,
82+
err: (error) => `Error: ${error.message}`,
83+
});
7284

73-
```typescript
74-
const role = okOr(result, "guestUser");
75-
```
85+
// Ignore errors and use a default value for when you don't care about the error
86+
87+
const data = okOr(result, { message: "Default message" });
7688

77-
Now `role` is gonna be either the value from the db, or if there was an error, `"guestUser"`.
89+
// If need be, you can throw an error if the Result is Err
7890

79-
<br>
91+
try {
92+
const value = okOrThrow(result);
93+
console.log(value.message);
94+
} catch (error) {
95+
console.error("Error was thrown:", error);
96+
}
97+
98+
// Returned values can be transformed/mapped quickly
99+
100+
const uppercased = mapOk(result, (value) => value.toUpperCase());
101+
102+
// The same is true for errors, and several mapping functions are provided
103+
104+
const betterError = mapErr(result, (error) => `Custom error: ${error.message}`);
105+
```
80106

81-
To see the library used in a project, checkout out [ahmeddots/oswald](https://github.com/ahmeddots/oswald).
107+
More information can be found as part of function documentation, which can be viewed in your editor or in the source code.

biome.json

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
{
2+
"$schema": "https://biomejs.dev/schemas/2.0.5/schema.json",
3+
"vcs": {
4+
"enabled": false,
5+
"clientKind": "git",
6+
"useIgnoreFile": false
7+
},
8+
"files": {
9+
"ignoreUnknown": false
10+
},
11+
"formatter": {
12+
"enabled": true,
13+
"indentStyle": "tab"
14+
},
15+
"linter": {
16+
"enabled": true,
17+
"rules": {
18+
"recommended": true
19+
}
20+
},
21+
"javascript": {
22+
"formatter": {
23+
"quoteStyle": "double"
24+
}
25+
},
26+
"assist": {
27+
"enabled": true,
28+
"actions": {
29+
"source": {
30+
"organizeImports": "on"
31+
}
32+
}
33+
}
34+
}

package.json

Lines changed: 15 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -5,11 +5,12 @@
55
"typescript",
66
"error-handling",
77
"try-catch",
8-
"erros"
8+
"errors"
99
],
10+
"version": "2.0.0",
1011
"repository": {
1112
"type": "git",
12-
"url": "https://github.com/ahmeddots/tryresult.git"
13+
"url": "https://github.com/ahme-dev/tryresult.git"
1314
},
1415
"publishConfig": {
1516
"access": "public"
@@ -28,15 +29,23 @@
2829
"build-fast": "tsup src --format cjs,esm",
2930
"build": "pnpm run build-fast --dts",
3031
"test": "vitest run",
32+
"size": "size-limit",
3133
"prepublishOnly": "pnpm run build"
3234
},
35+
"size-limit": [
36+
{
37+
"path": "src/index.ts"
38+
}
39+
],
3340
"license": "MIT",
3441
"devDependencies": {
42+
"@biomejs/biome": "2.0.5",
43+
"@size-limit/preset-small-lib": "^11.2.0",
3544
"@types/node": "^20.2.1",
36-
"prettier": "2.8.4",
45+
"size-limit": "^11.2.0",
3746
"tsup": "6.6.3",
3847
"typescript": "4.9.5",
39-
"vite": "^4.3.8",
4048
"vitest": "0.28.5"
41-
}
42-
}
49+
},
50+
"type": "module"
51+
}

0 commit comments

Comments
 (0)