Passed
Push — main ( d13a4d...a77d33 )
by Lorenzo
01:16 queued 14s
created

src/core/errors.ts   A

Complexity

Total Complexity 5
Complexity/F 0

Size

Lines of Code 66
Function Count 0

Duplication

Duplicated Lines 0
Ratio 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 5
eloc 52
mnd 5
bc 5
fnc 0
dl 0
loc 66
ccs 26
cts 26
cp 1
rs 10
bpm 0
cpm 0
noi 0
c 0
b 0
f 0
1
export declare type ResultOk<T> = {
2
  ok: true,
3
  value: T,
4
};
5
6
export declare type ResultError<E = Error> = {
7
  ok: false,
8
  error: E,
9
};
10
11
export declare type Result<T, E = Error> = ResultOk<T> | ResultError<E>;
12
13
export declare type ResultAsync<T> = Promise<Result<T>>;
14
15 27
export const isOk = <T>(result: Result<T>): result is ResultOk<T> => result.ok;
16
17 67
export const isError = <T>(result: Result<T>): result is ResultError => !result.ok;
18
19 11
const commuteError = (thrown: any) => {
20 14
  if (thrown instanceof Error) {
21 10
    return thrown;
22
  }
23 4
  return new Error(String(thrown));
24
};
25
26 11
export const wrap = <T>(fn: () => T | Promise<T>): Result<T> | Promise<Result<T>> => {
27 67
  try {
28 67
    const result = fn();
29
30 62
    if (result instanceof Promise) {
31 23
      return result
32 14
        .then((value) => ({ ok: true as const, value }))
33 9
        .catch((error) => ({ ok: false as const, error: commuteError(error) }));
34
    }
35
36 39
    return {
37
      ok: true as const,
38
      value: result,
39
    };
40
  } catch (error) {
41 5
    return {
42
      ok: false as const,
43
      error: commuteError(error),
44
    };
45
  }
46
};
47
48 11
export const unwrap = <T>(result: Result<T>): T => {
49 11
  if (isOk(result)) {
50 6
    return result.value;
51
  }
52 5
  throw result.error;
53
};
54
55 11
export const unwrapAsync = async <T>(resultAsync: ResultAsync<T>): Promise<T> => {
56 4
  const result = await resultAsync;
57 3
  if (isOk(result)) {
58 1
    return result.value;
59
  }
60 2
  throw result.error;
61
};
62
63 11
export const wrapValue = <T>(value: T): Result<T> => ({ ok: true as const, value });
64
65
export const wrapError = <E = Error>(error: E): ResultError<E> => ({ ok: false as const, error });
66