-
Notifications
You must be signed in to change notification settings - Fork 0
/
errThenEnd.ts
52 lines (46 loc) · 1.65 KB
/
errThenEnd.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import type { MaybePromise, Modifier } from '@/types'
import { FlowMissModifierException, isPromise } from '@/utils'
import type { Result } from './result'
import { err, ok } from './result'
/**
* Call `fn` if `result` is failure, then exit flow.
*
* @example
* ```typescript
* const userInfo = (await flow(ok(filePath), andThen(readFileToStr), errThenEnd(notify), andThen(calcLineCount))).unwrapOr(0)
* ```
*
* {@link https://github.com/niuiic/fx-flow/blob/main/packages/test/src/flow/errThenEnd.spec.ts | More examples}
*/
function errThenEnd<A>(
fn: (err: string) => Promise<unknown>,
result: Result<A>,
modifier: Modifier
): MaybePromise<Result<A>>
function errThenEnd<A>(
fn: (err: string) => Promise<unknown>
): (result: Result<A>, modifier: Modifier) => MaybePromise<Result<A>>
function errThenEnd<A>(fn: (err: string) => unknown, result: Result<A>, modifier: Modifier): Result<A>
function errThenEnd<A>(fn: (err: string) => unknown): (result: Result<A>, modifier: Modifier) => Result<A>
function errThenEnd<A>(
fn: (err: string) => MaybePromise<unknown>,
result?: Result<A>,
modifier?: Modifier
): MaybePromise<Result<A>> | ((result: Result<A>, modifier: Modifier) => MaybePromise<Result<A>>) {
if (result === undefined) {
return (result: Result<A>, modifier: Modifier) => errThenEnd(fn, result, modifier)
}
if (modifier === undefined) {
throw new FlowMissModifierException()
}
if (result.isErr()) {
modifier({ done: true })
const res = fn(result.error()!)
if (isPromise(res)) {
return res.then(() => err(result.error()!))
}
return err(result.error()!)
}
return ok(result.unwrap())
}
export { errThenEnd }