UNPKG

@stnekroman/tstools

Version:

Set of handy tools for TypeScript development

92 lines (91 loc) 2.61 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Result = exports.Failure = exports.Success = void 0; var Success; (function (Success) { function isSuccessData(result) { return result instanceof Result ? result.isSuccess() : result.error === undefined && 'data' in result; } Success.isSuccessData = isSuccessData; })(Success || (exports.Success = Success = {})); var Failure; (function (Failure) { function isFailureData(result) { return result instanceof Result ? result.isFailure() : result.error !== undefined; } Failure.isFailureData = isFailureData; })(Failure || (exports.Failure = Failure = {})); class Result { constructor(_data, _error) { this._data = _data; this._error = _error; } static success(data) { return new Result(data, undefined); } static failure(error) { return new Result(undefined, error); } static from(serializable) { if (Success.isSuccessData(serializable)) { return new Result(serializable.data, undefined); } else if (Failure.isFailureData(serializable)) { return new Result(undefined, serializable.error); } else { throw new Error('Invalid Result type'); } } isSuccess() { return this._error === undefined; } isFailure() { return this._error !== undefined; } get data() { if (this.isSuccess()) return this._data; throw new Error('Cannot get data from a Failure'); } get error() { if (this.isFailure()) return this._error; throw new Error('Cannot get error from a Success'); } map(f) { return this.isSuccess() ? Result.success(f(this._data)) : this; } flatMap(f) { return this.isSuccess() ? f(this._data) : this; } toJSON() { return { data: this._data, error: this._error, }; } toString() { return JSON.stringify(this.toJSON()); } [Symbol.for('nodejs.util.inspect.custom')]() { return this.toJSON(); } static groupResults(results) { return results.reduce((container, result) => { if (result.isSuccess()) { container.successes.push(result); } else { container.failures.push(result); } return container; }, { successes: [], failures: [], }); } } exports.Result = Result;