safe-result
Version:
Create safe results that are either successes or failures
109 lines • 2.66 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.failure = exports.success = exports.SuccessAndFailureResult = exports.FailureResult = exports.SuccessResult = void 0;
const internal_1 = require("./internal");
/**
* A class representing a successful result
*/
class SuccessResult {
constructor(data) {
this._res = data;
}
get result() {
return this._res;
}
get error() {
return undefined;
}
/** Returns a tuple with `[successValue, undefined]` */
unwrap() {
return [this.result, undefined];
}
/** Always returns `true` */
get success() {
return true;
}
/** Always returns `false` */
get failure() {
return false;
}
}
exports.SuccessResult = SuccessResult;
/**
* A class representing an error result
*/
class FailureResult {
constructor(error) {
this._res = error;
}
get result() {
return undefined;
}
get error() {
return this._res;
}
/** Returns a tuple with `[undefined, failureValue]` */
unwrap() {
return [undefined, this.error];
}
/** Always returns `false` */
get success() {
return false;
}
/** Always returns `true` */
get failure() {
return true;
}
}
exports.FailureResult = FailureResult;
/**
* Class representing a result that can both have successful and failed
* values. This is only used internally by and returned from [[allSettled]]
*/
class SuccessAndFailureResult {
constructor(res, err) {
this._res = res;
this._err = err;
}
get result() {
return this._res;
}
get error() {
return this._err;
}
unwrap() {
return [this._res, this._err];
}
get success() {
return (0, internal_1.isUndefinedOrNull)(this._res)
? false
: Array.isArray(this._res)
? this._res.length > 0
: true;
}
get failure() {
return (0, internal_1.isUndefinedOrNull)(this._err)
? false
: Array.isArray(this._err)
? this._err.length > 0
: true;
}
}
exports.SuccessAndFailureResult = SuccessAndFailureResult;
/**
* Utility function for creating a [[SuccessResult]] instance
* @param result
*/
function success(result) {
return new SuccessResult(result);
}
exports.success = success;
/**
* Utility function for creating a [[FailureResult]] instance
* @param error
*/
function failure(error) {
return new FailureResult(error);
}
exports.failure = failure;
//# sourceMappingURL=result.js.map