Compare commits

..

2 commits

Author SHA1 Message Date
Anton Nesterov a6edb3505b
docs
Some checks are pending
Publish / publish (push) Waiting to run
2024-10-19 15:50:34 +02:00
Anton Nesterov 3cff57ccac
publish 2024-10-19 15:33:42 +02:00
2 changed files with 22 additions and 3 deletions

View file

@ -16,4 +16,4 @@ jobs:
- uses: actions/checkout@v4 - uses: actions/checkout@v4
- name: Publish package - name: Publish package
run: npx jsr publish run: npx jsr publish --allow-slow-types

23
grip.ts
View file

@ -9,6 +9,9 @@ interface Status {
of(cls: any): boolean; of(cls: any): boolean;
} }
/**
* Error result
*/
export class Err extends Error { export class Err extends Error {
Ok() { Ok() {
return false; return false;
@ -36,6 +39,9 @@ export class Err extends Error {
} }
} }
/**
* Successful result
*/
export class Ok { export class Ok {
Ok() { Ok() {
return true; return true;
@ -148,14 +154,27 @@ type Unwrap<T> =
? U ? U
: T; : T;
export type SafeResult<T> = type SafeResult<T> =
T extends Promise<any> T extends Promise<any>
? Promise<Result<Unwrap<T>>> ? Promise<Result<Unwrap<T>>>
: T extends () => Promise<any> : T extends () => Promise<any>
? Promise<Result<Unwrap<T>>> ? Promise<Result<Unwrap<T>>>
: Result<Unwrap<T>>; : Result<Unwrap<T>>;
export function grip<T>(action: T) { /**
* Grip wraps functions, promises or generators and returns it as a result.
* The result can be handled as an object { value, status }, or as a tuple [value, object].
* The result and status interfaces have the methods `ok(), fail(), of(Error)` to check the status:
*
* ```javascript
* const json = grip(response.body.joson())
* if (json.of(SyntaxError)) {
* // handle parse error
* }
* // handle json.value
* ```
*/
export function grip<T>(action: T): SafeResult<T> {
if (action instanceof Promise) { if (action instanceof Promise) {
return promise<T>(action) as SafeResult<T>; return promise<T>(action) as SafeResult<T>;
} }