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

try-fallback

v2.0.0

Published

Return the result of the first successful implementation in a set.

Downloads

24

Readme

try-fallback

Try a set of functions in order, one at a time, resolving with the result of the first successful implementation.

Why?

Utilizing this pattern can help you keep your business logic nice and tidy while solving problems like resilience and complex multi-strategy operations

Installation

With yarn:

yarn add try-fallback

or with npm:

npm install try-fallback

Usage

Here's a useless example just to show you how it works:

import { tryFallback } from 'try-fallback';

const [implementation, result] = await tryFallback([
  ['thisOneFails', () => {
    throw new Error('failed!');
  }],
  ['addOne', i => i + 1],
])(1);

console.log(implementation);
// addOne

console.log(result);
// 2

Now for some more interesting examples:

For Resilience

The simplest and most obvious use for tryFallback is to provide resilience to an operation that is possibly error-prone by retrying the operation with varying strategies.

In this contrived example we're doing a DNS lookup against three different DNS servers. In the case that the first fails, tryFallback will invoke the second. If the second fails it will invoke the third. Since we only have three implementations, if the third fails, tryFallback will throw an error indicating that all available implementations have failed.

import { tryFallback } from 'try-fallback';

const dnsLookup = tryFallback([
  ['serverA', domainServerA.lookup],
  ['serverB', domainServerB.lookup],
  ['serverC', domainServerC.lookup],
]);

const [implementation, ipAddress] = await dnsLookup(name);

For managing complex business logic

Another use for tryFallback is to encapsulate complicated business logic into self-contained implementations which throw under certain conditions to purposefully pass the operation to the next implementation in the set. The implementations are ordered by priority (the first implementation is preferable to the second and so on).

In this example we want to provide a recommendation to a user about what to watch next on a streaming platform.

import { tryFallback } from 'try-fallback';

// Here's an example "implementation" of a recommendation operation which
// suggests the next episode in a series.
async function nextEpisodeImplementation() {
  const nextEpisode = await getNextEpisode();

  if (!nextEpisode) {
    throw Error("We do not have a next episode. The current video must be the last one!");
  }

  if (nextEpisode.isWatched()) {
    throw new Error("The user has already watched the next video. Let's recommend something else.");
  }

  return nextEpisode;
}

// I'll keep this brief and not pseudo-code the other two implementations. Hopefully you get the gist.

const getRecommendation = tryFallback([
  ['nextEpisode', nextEpisodeImplementation],
  ['fromSimilarSeries', similarSeriesImplementation],
  ['fromWatchlist', watchlistImplementation],
])

const [implementation, recommendation] = await getRecommendation();

Error handling

If you need to respond to errors thrown within the implementation functions, you can pass an error handler to tryFallback as the second argument:

import { tryFallback } from 'try-fallback';

const doAThing = tryFallback(
  [
    ['thisOneFails', () => {
      throw new Error('Whoopsie!');
    }],
    ['addOne', i => i + 1],
  ],
  // Error handler:
  ([imp, error]) => {
    console.log(`failed implementation: ${imp}`);
    console.log(`error message: ${error.message}`);
  }
);

const [implementation, result] = await doAThing(1);
// failed implementation: thisOneFails
// error message: Whoopsie!

console.log(implementation);
// addOne

console.log(result);
// 2

API

tryFallback(implementations, errorHandler?)

Returns a unary function which, when invoked, will invoke each implementation function in order, passing its own single argument to each and returning a promise which resolves with the result of the first successful implementation. If all implementations throw, the promise will be rejected with an error.

implementations: An array of tuples containing the implementation name in the first position and the implementation function in the second.

For example:

[
  ['addOne', i => i + 1],
  ['addTwo', i => i + 2]
]

errorHandler?: An optional error handling function which is invoked each time an implementation throws an error, triggering a fallback. The error handler accepts two arguments. The first is the implementation name. The second is the error that was thrown.

For example:

(implementation, error) => {
  console.error(`Implementation ${implementation} failed: ${error.message}`);
}