/** * A `Result` can be used to store the result of an operation. The operation can either be successful or considered as a failure. * This class has been proposed by [Khalil Stemmler](https://khalilstemmler.com/articles/enterprise-typescript-nodejs/handling-errors-result-class/). * * * Results are **immutable** * * * @specfield isFailure (boolean): determines whether or not the operation has failed * @specfield isSuccess (boolean): determines whether or not the operation is successful * @specfield error (Error) : contains the error causing the failure (**if the operation failed**) * @specfield value (`T`) : contains the result of the operation (**if it is successful**) * * * @typeparam T Return type if the result is successful */ export class Result { public isSuccess: boolean; public isFailure: boolean public error : Error; private _value : T; /** * Creates a new `Result` so that: * * this_post.isSuccess = isSuccess && * * this_post.isFailure = !isSuccess && * * this_post.error = error if isSuccess = = false && * * this_post.value = value if isSuccess = = true * * @param isSuccess Determines whether or not the operation is a success * @param error The error to be held in case the operation failed * @param value The resulting value if the operation was successful */ private constructor (isSuccess: boolean, error?: Error, value?: T) { if (isSuccess && error) throw new Error(`InvalidOperation: A result cannot be successful and contain an error`); if (!isSuccess && !error) throw new Error(`InvalidOperation: A failing result needs to contain an error message`); this.isSuccess = isSuccess; this.isFailure = !isSuccess; this.error = error; this._value = value; Object.freeze(this); } /** * @throws A new `Error` if this.isFailure = = true * @willreturn Otherwise, returns this.value */ public getValue () : T { if (!this.isSuccess) throw new Error(`Cant retrieve the value from a failed result`) return this._value; } /** * @willreturn A new `Result` `r` considered as successful and so that `r`.value = value * @param value The value to be returned if the operation is successful * @typeparam U Type of `Result` to be held as value */ public static ok (value?: U) : Result { return new Result(true, null, value); } /** * @willreturn A new `Result` `r` considered as a failure and so that `r`.error = error * @param value The value to be returned if the operation is successful * @typeparam U Type of `Result` to be held as value */ public static fail (error: Error): Result { return new Result(false, error); } /** * @willreturn A new `Result` `r`so that `r`.isFailure is true if any of the results held in `results` is a failure * @param results Set of results to combine to get an overall result */ public static combine (results: Result[]) : Result { for (let result of results) if (result.isFailure) return result; return Result.ok(); } };