npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

chain-of-actions

v0.10.0

Published

Railway error management implementation in Typescript

Downloads

664

Readme

Objective

This project aims to provide a typed error management for typescript code.

The problem

Typescript error management is based on the try/catch statements and this approach doesn't provide a strong-type management for error handling.

try {
  const user = await getUser("id");
} catch (error: unknown) {
  // error can be here of any type
}

Quick Start

A method like:

async function getUser(id: number): Promise<User> {
  /* */
}

Can be replaced by:

async function getUser(
  id: number,
): PromisedResult<User, DatabaseError | MissingDataError> {
  /* */
}

Calling this method will return two possible results:

  • {success: true, value: {...}} - A success result, where value will be a User instance
  • {success: false, error: {...}} - a failed result, where error will be a DatabaseError | MissingDataError instance.

To implement this method, we can use a few helpers from the Block and Chain class:

async function getUser(
  id: number,
): PromisedResult<User, DatabaseError | MissingDataError> {
  return Chain.start()
    .add(() =>
      Block.convert({
        try: () => database.get("User", id),
        catch: (e) => new DatabaseError(e),
      }),
    )
    .onSuccess((user) =>
      user ? Block.succeed(user) : Block.fail(new MissingDataError("User", id)),
    );
}

| Code | Explanation | | -------------------- | ------------------------------------------------------------------------- | | Chain.start() | starts a chain of actions with a specific data | | .add(action) | adds a new node to the chain | | .onSuccess(action) | adds a new node that will execute its action if the previous node succeed | | Block.succeed() | Create a successful response | | Block.fail() | Create a failed response |

[!NOTE] This example can still be improved: the current implementation uses a database object : Where is it initialized? How are the error managed for it?

Architecture

This library is based on the Railway design pattern.

Railway Oriented Programming is based on the metaphor of a railway track, where operations can either succeed (the "right track") or fail (the "wrong track"). The idea is to structure the code in such a way that successful operations continue down one path, while failures are handled separately, allowing for a clean separation of concerns.

In this library, we consider that three tracks should exist as our operations can either succeed (the "right track"), raise an error (the "error track") or endure an unexpected failure (the "failure track").

For instance, a call to an operation like getUser(id) could:

  • succeed and return a User instance,
  • raise an error when the id doesn't exist in the database or if the connection is not available,
  • failed unexpectingly if the server run out of memory during the operation.

To achieve this, the library proposes the following result types:

  • SuccessResult<Data> - represents the successful result of an operation
  • FailureResult<Error> - represents the error raised by an operation
  • Result<Data, Error> - the union of SuccessResult and FailureResult
  • PromisedResult<Data, Error> - a Promise returning a Result

All those types don't contain methods and remain data type that can be serialized (to be usable as part of RPC flow for instance).

The notion of "Railway" is splited into 3 core concepts:

  • The Action, a function that executes a process based on a specific data and context and returns a PromisedResult.
  • The Node that encapsulates an action to provides extra methods.
  • The Chain that groups various nodes to provide a service.