@synet/credential
Version:
VC Credentials - Simple, Robust, Unit-based Verifiable Credentials service
111 lines (110 loc) • 3.12 kB
JavaScript
"use strict";
/**
* Minimal Result pattern for @synet/credential
*
* API-compatible with @synet/patterns Result but self-contained.
* Removes unused methods (map, flatMap, recover, ensure, combine).
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.Result = void 0;
/**
* A simple and versatile Result pattern implementation
* Used for representing the outcome of operations that might fail
*/
class Result {
constructor(_isSuccess, _value, _error) {
this._isSuccess = _isSuccess;
this._value = _value;
this._error = _error;
}
/**
* Returns whether this Result represents a successful operation
*/
get isSuccess() {
return this._isSuccess;
}
/**
* Returns whether this Result represents a failed operation
*/
get isFailure() {
return !this._isSuccess;
}
/**
* Returns the success value
* @throws Error if called on a failed result
*/
get value() {
if (!this.isSuccess) {
throw new Error("Cannot get value from a failed result");
}
return this._value;
}
/**
* Returns the error details if this is a failure result
*/
get error() {
return this._error;
}
/**
* Returns the error message if this is a failure result
*/
get errorMessage() {
return this._error?.message;
}
/**
* Returns the error cause if this is a failure result
*/
get errorCause() {
return this._error?.cause;
}
/**
* Creates a successful result with a value
* @param value The success value
*/
static success(value) {
return new Result(true, value);
}
/**
* Creates a failure result with a message, optional cause, and optional context data
* @param message Error message describing what went wrong
* @param cause Optional underlying error that caused the failure
* @param data Optional additional context data for debugging
*/
static fail(message, cause, ...data) {
return new Result(false, undefined, {
message,
cause,
data: data.length > 0 ? data : undefined,
});
}
/**
* Executes the given callback if this is a success result
* @param fn Function to execute with the success value
* @returns This result, for method chaining
*/
onSuccess(fn) {
if (this.isSuccess) {
fn(this.value);
}
return this;
}
/**
* Executes the given callback if this is a failure result
* @param fn Function to execute with the error details
* @returns This result, for method chaining
*/
onFailure(fn) {
if (this.isFailure && this._error) {
fn(this._error.message, this._error.cause, this._error.data);
}
return this;
}
/**
* Checks if the result is null
* @returns true if the result is null, false otherwise
*/
isNull() {
return this.isSuccess && this.value === null;
}
}
exports.Result = Result;