All files ResultUtils.ts

86.44% Statements 51/59
77.77% Branches 21/27
82.14% Functions 23/28
86.44% Lines 51/59

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 2371x 1x   1x                                                                     4x           4x 24x       18x 18x             2x           2x       2x 1x   2x                                                             2x 2x 2x 5x 5x 1x   4x     1x     2x 1x                   4x       4x       4x         8x 1x         1x             7x 5x 5x 4x 4x 4x     5x 4x     4x     1x       4x                             2x   2x   12x 9x 2x         1x                                 2x   2x   12x 9x       1x                            
import delay from "delay";
import { err, ok, ResultAsync, Result, okAsync, errAsync } from "neverthrow";
 
export class ResultUtils {
  static combine<T, T2, T3, T4, T5, E, E2, E3, E4, E5>(
    asyncResultList: [
      ResultAsync<T, E>,
      ResultAsync<T2, E2>,
      ResultAsync<T3, E3>,
      ResultAsync<T4, E4>,
      ResultAsync<T5, E5>,
    ],
  ): ResultAsync<[T, T2, T3, T4, T5], E | E2 | E3 | E4 | E5>;
  static combine<T, T2, T3, T4, E, E2, E3, E4>(
    asyncResultList: [
      ResultAsync<T, E>,
      ResultAsync<T2, E2>,
      ResultAsync<T3, E3>,
      ResultAsync<T4, E4>,
    ],
  ): ResultAsync<[T, T2, T3, T4], E | E2 | E3 | E4>;
  static combine<T, T2, T3, E, E2, E3>(
    asyncResultList: [
      ResultAsync<T, E>,
      ResultAsync<T2, E2>,
      ResultAsync<T3, E3>,
    ],
  ): ResultAsync<[T, T2, T3], E | E2 | E3>;
  static combine<T, T2, E, E2>(
    asyncResultList: [ResultAsync<T, E>, ResultAsync<T2, E2>],
  ): ResultAsync<[T, T2], E | E2>;
  static combine<T, E>(
    asyncResultList: ResultAsync<T, E>[],
  ): ResultAsync<T[], E>;
 
  static combine<T, E>(
    asyncResultList: ResultAsync<T, E>[],
  ): ResultAsync<T[], E> {
    return ResultAsync.fromPromise(Promise.all(asyncResultList), (e) => {
      return e as E;
    }).andThen(ResultUtils.combineResultList);
  }
 
  static combineResultList<T, E>(resultList: Result<T, E>[]): Result<T[], E> {
    return resultList.reduce((acc: Result<T[], E>, result) => {
      return acc.isOk()
        ? result.isErr()
          ? err(result.error)
          : acc.map((values) => {
              values.push(result.value);
              return values;
            })
        : acc;
    }, ok([]));
  }
 
  static race<T, E>(asyncResultList: ResultAsync<T, E>[]): ResultAsync<T, E> {
    return ResultAsync.fromPromise(Promise.race(asyncResultList), (e) => {
      return e as E;
    }).andThen(ResultUtils.resultRace);
  }
 
  static resultRace<T, E>(result: Result<T, E>): Result<T, E> {
    return result.isErr() ? err(result.error) : ok(result.value);
  }
 
  static fromThrowableResult<T, E>(throwableCallback: () => T): Result<T, E> {
    const throwable = Result.fromThrowable(throwableCallback, (err) => {
      return err as E;
    });
    return throwable();
  }
 
  static executeSerially<T, E>(
    funcList: (() => ResultAsync<T, E>)[],
  ): ResultAsync<T[], E> {
    // const results = new Array<T>();
 
    // // for (const func of funcList) {
    // //   func().map((val) => {})
    // // }
 
    // try {
    //   funcList.reduce(
    //     (p: ResultAsync<void, E>, x) =>
    //       p.andThen(_ => {
    //         return x()
    //           .map((result) => {
    //             results.push(result);
    //           })
    //           .mapErr((e) => {
    //             throw e;
    //           });
    //       }),
    //     okAsync<void, E>(undefined)
    //   );
    // }
    // catch (e) {
    //   return errAsync(e);
    // }
 
    const func = async () => {
      const results = new Array<T>();
      for (const func of funcList) {
        const result = await func();
        if (result.isErr()) {
          throw result.error;
        } else {
          results.push(result.value);
        }
      }
      return results;
    };
 
    return ResultAsync.fromPromise(func(), (e) => {
      return e as E;
    });
  }
 
  static backoffAndRetry<T, E extends Error>(
    func: () => ResultAsync<T, E>,
    acceptableErrors: Function[],
    maxAttempts?: number,
    baseSeconds = 5,
  ): ResultAsync<T, E> {
    Iif (maxAttempts != null && maxAttempts < 1) {
      throw new Error("maxAttempts must be 1 or more!");
    }
 
    Iif (baseSeconds < 1) {
      throw new Error("baseSeconds must be 1 or more!");
    }
 
    const runAndCheck = (
      currentAttempt: number,
      nextAttemptSecs: number,
      lastError: E | null,
    ): ResultAsync<T, E> => {
      if (maxAttempts != null && currentAttempt > maxAttempts) {
        Iif (lastError == null) {
          throw new Error(
            "Error before first function run; logical error! maxAttempts must be 1 or more!",
          );
        }
        return errAsync(lastError);
      }
 
      // Check the result. If it's not an error, we're done!
      // If it's an error, check the error type against acceptableErrors. If it's in the list,
      // wait some amount of time and try again.
      // If it is not in the list, return the error and stop.
      return func().orElse((e) => {
        let retry = false;
        for (const acceptableError of acceptableErrors) {
          Eif (e instanceof acceptableError) {
            retry = true;
            break;
          }
        }
        if (retry) {
          return ResultAsync.fromSafePromise<void, never>(
            delay(nextAttemptSecs),
          ).andThen(() => {
            return runAndCheck(++currentAttempt, nextAttemptSecs * 2, e);
          });
        }
        return errAsync(e);
      });
    };
 
    return runAndCheck(1, baseSeconds, null);
  }
 
  /**
   * filter() is a normal filter method that works with async callbacks.
   * This works like a nomral array filter() call, except the callback returns
   * a ResultAsync<boolean> instead of just boolean.
   * @param arr the source array
   * @param callback a function that returns a ResultAsync<boolean>; if it returns true then the source value is included in the result.
   * @returns a ResultAsync containing an array of source values where the callback returns true.
   */
  static filter<T, E extends Error>(
    arr: T[],
    callback: (val: T) => ResultAsync<boolean, E>,
  ): ResultAsync<T[], E> {
    const filterVals = new Array<T>();
 
    return ResultUtils.combine(
      arr.map((val) => {
        return callback(val).map((result) => {
          if (result) {
            filterVals.push(val);
          }
        });
      }),
    ).map(() => {
      return filterVals;
    });
  }
 
  /**
   * map() is a way to combine multiple async callbacks.
   * This works like a normal array map() call, except the callbacks return ResultAsync.
   * It will combine all the results and return a single ResultAsync with an array of the mapped
   * values.
   * @param arr The source array of objects
   * @param callback A function that returns a ResultAsync and a value
   * @returns A ResultAsync containing an array of the mapped values or the first error.
   */
  static map<T, U, E extends Error>(
    arr: T[],
    callback: (val: T) => ResultAsync<U, E>,
  ): ResultAsync<U[], E> {
    const mapVals = new Array<U>();
 
    return ResultUtils.combine(
      arr.map((val) => {
        return callback(val).map((result) => {
          mapVals.push(result);
        });
      }),
    ).map(() => {
      return mapVals;
    });
  }
 
  static delay(ms: number): ResultAsync<void, never> {
    return ResultAsync.fromSafePromise(
      new Promise((resolve) => {
        setTimeout(() => {
          resolve();
        }, ms);
      }),
    );
  }
}