0.2.1 • Published 2 years ago

@kwyjibo-developments/typescript-result v0.2.1

Weekly downloads
-
License
MIT
Repository
-
Last release
2 years ago

Result pattern for TypeScript

Build status npm

Motivation

In an ideal world, all method calls will execute without any failures or errors. Practically, however, method calls will sometimes fail or error due to invalid input or downstream issues with dependencies of the method (e.g. HTTP call failures). Ideally, the method will be able to advise its caller if completed its task successfully, or if there was an issue in its execution. The Result Pattern was designed to permit failures and errors to be handled by the method call, as well as provide information to the caller about the result of its computation. This package was created to provide a simple implementation of this pattern for TypeScript and JavaScript.

Without using the result pattern, typical method calls that may throw an error that needs to be handled by the parent and may need to be propagated up several parent calls to be properly handled. In the example below, we consider a method that may fail or throw an error that can be handled by its immediate parent without using Results.

function caller() : void {
    try {
        const value = callMe();
        if (value == null) {
            // handle the case where an invalid value was returned
            return; // we don't want to do more processing
        }

        // do work with value
    } catch (err) {
        // handle the error that was thrown from the computation as relevant
    }
}

function callMe() : number | null {
    // this method may throw an error
    const value = someComputation();

    if (isValid(value)) {
        return value;
    }
    // value is not valid, so return null as default to indicate failure
    return null;
}

With the use of Result objects, we can make the implementation of the caller much more straightforward and clear about exactly how it is operating using the result of callMe.

function caller() : void {

    callMe()
        .match((value) => {
            // do work with the value
        }, (theResult) => {
            // handle the case where an invalid value was returned
        },(theResult) => {
            // handle the error that was thrown from the computation as relevant
        }
    );
                
}

function callMe() : ValueResult<number> {
    try {
        // this method may throw an error
        const value = someComputation(); // returns number

        if (isValid(value)) {
            return ValueResult.Success<number>(value);
        }
        
        // value is not valid, so return a failure instance
        return ValueResult.Failed<number>("The computed value is invalid");

    } catch (err) {
        // we can now encapsulate the error in this method, so that it is
        //  not propagated up to parent methods
        return ValueResult.Error<number>(err);
    }
}

Features

  • Simple framework that provides both void and value Result implementations
  • Suitable for both JavaScript and TypeScript

Installation

npm install @kwyjibo-developments/typescript-result

Usage

import { ValueResult } from '@kwyjibo-developments/typescript-result';

function isSystemStateValid() : ValueResult<boolean> {
    try {

        // we don't control this function
        // we know it returns null if it fails, or a boolean if it
        // completes successfully
        const result = someSystemStateIsValid();

        if (result == null) {
            return ValueResult.Failed("The validation check was unable to be completed.");
        }
        
        return ValueResult.Success(result);

    } catch (err) {
        return ValueResult.Error<boolean>(err, "An unexpected error when performing the validation.");
    }
}

In the above example, it is noted here that Success and Failed do not correspond to the state of the system being measured in the someSystemStateIsValid() function. Rather, they correspond to the ability to execute the function successfully and the type of result that it returns. The outputs of this function are shown below, along with their corresponding explanations.

  • ValueResult Success with value true: The function someSystemStateIsValid completed without error and the current system state is valid.
  • ValueResult Success with value false: The function someSystemStateIsValid completed without error and the current system state is not valid.
  • ValueResult Failed: The function someSystemStateIsValid did not complete successfully. It failed with an error expected by the author of the function and returned without throwing an Error.
  • ValueResult Error: The function someSystemStateIsValid did not complete successfully. It failed with an error not expected by the author of the function and returned by throwing an Error.

The match extension method is available to provide a fluent interface for chaining the outputs of a result with future actions to perform.

import {Result, ValueResult} from '@kwyjibo-developments/typescript-result';

function doSomething() : Result { } // implementation omitted

function doSomethingElse() : ValueResult<number> { } // implementation omitted

function handler() : void {
    doSomething()                       // Line 1
        .match(
            doSomethingElse,
            failureCallback,
            errorCallback
        )
        .match(
            completeCallback,
            someOtherFailureCallback,
            someOtherErrorCallback
        );
}
0.2.1

2 years ago

0.2.0

2 years ago

0.1.2

3 years ago

0.1.1

3 years ago

0.1.3

3 years ago

0.1.0

3 years ago