Skip to content

Commit

Permalink
Add guard
Browse files Browse the repository at this point in the history
  • Loading branch information
bkiac committed Nov 3, 2023
1 parent 4ad68a1 commit 5203407
Showing 1 changed file with 22 additions and 0 deletions.
22 changes: 22 additions & 0 deletions src/helpers/module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@ import type {PromiseResult} from "../result/promise"

export type ResultModuleErrorHandler<E extends ResultError, F extends ResultError> = (error: E) => F

type Fn = (...args: any[]) => any
type AsyncFn = (...args: any[]) => Promise<any>

export class ResultModule<E extends ResultError> {
private constructor(private readonly handleError: ErrorHandler<E>) {}

Expand Down Expand Up @@ -41,6 +44,25 @@ export class ResultModule<E extends ResultError> {
return tryAsyncFnWith(f, (error) => h(this.handleError(error)))
}

guard<T extends Fn>(f: T) {
return (...args: Parameters<T>) => this.tryFn(() => f(...args))
}

guardWith<T extends Fn, F extends ResultError>(f: T, h: ResultModuleErrorHandler<E, F>) {
return (...args: Parameters<T>) => this.tryFnWith(() => f(...args), h)
}

guardAsync<T extends AsyncFn>(f: T) {
return (...args: Parameters<T>) => this.tryAsyncFn(() => f(...args))
}

guardAsyncWith<T extends AsyncFn, F extends ResultError>(
f: T,
h: ResultModuleErrorHandler<E, F>,
) {
return (...args: Parameters<T>) => this.tryAsyncFnWith(() => f(...args), h)
}

static with<E extends ResultError>(handleError: ErrorHandler<E>): ResultModule<E> {
return new ResultModule(handleError)
}
Expand Down

0 comments on commit 5203407

Please sign in to comment.