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

happy-handler

v1.0.0

Published

A flexible, type-safe handler to simplify handling success, error, and unknown responses for promises.

Downloads

2

Readme

HappyHandler

HappyHandler is a flexible, type-safe handler for promises that simplifies the process of handling success, error, and unknown responses. It allows you to forget about manually catching errors or validating response types, making your code cleaner and easier to manage.

Features

  • 🧠 Type-safe handling: Define your success and error response types easily.
  • Timeout support: Automatically cancels long-running operations with a configurable timeout.
  • 💼 Plug-and-play: Works with any promise-returning function, including libraries like Axios or native async functions.
  • 🔧 Customizable: Handle unknown responses, success and error in a structured way.

Installation

You can install the library via NPM:

npm install happy-handler

Basic Usage

Example with axios

import HappyHandler from 'happy-handler';
import axios from 'axios';

// Create an instance of Axios
const axiosInstance = axios.create({
  baseURL: 'https://jsonplaceholder.typicode.com',
  timeout: 5000, // Timeout for Axios (5 seconds)
});

// Define response and error interfaces
interface ValidRes {
  id: number;
  title: string;
}

interface ValidError {
  errorCode: string;
}

// Instantiate the handler
const handler = new HappyHandler({
  timeout: 30000,  // Custom timeout for the handler (30 seconds)
});

// Handle an Axios request
handler.handle({
  func: () => axiosInstance.get('/posts/1'),
  validResponses: [ValidRes],
  validErrors: [ValidError],
  onSuccess: (data) => {
    console.log('Successful response:', data);
  },
  onError: (error) => {
    console.log('Handled error:', error);
  },
  onUnknown: (unknown) => {
    console.warn('Unknown case detected:', unknown);
  },
});

Example with a Custom Async Function

import HappyHandler from 'happy-handler';

// Custom function returning a promise
async function fetchData(): Promise<{ data: string }> {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve({ data: 'Some fetched data' });
    }, 1000);
  });
}

// Define response and error interfaces
interface FetchSuccess {
  data: string;
}

interface FetchError {
  error: string;
}

// Instantiate the handler
const handler = new HappyHandler({
  timeout: 5000,  // 5 seconds timeout
});

// Handle a custom async function
handler.handle({
  func: fetchData,
  validResponses: [FetchSuccess],
  validErrors: [FetchError],
  onSuccess: (data) => {
    console.log('Custom function successful:', data);
  },
  onError: (error) => {
    console.error('Custom function error:', error);
  },
  onUnknown: (unknown) => {
    console.warn('Unknown case in custom function:', unknown);
  },
});

API Reference

| Method | Description | | -------- | ------- | | handle | Executes the passed function and processes success, error, or unknown responses based on the configuration. |

handle(config: HandleConfig)

Executes any function that returns a promise and handles the result based on predefined response and error types.

Parameters:

| Parameter | Type | Description | | --------- | ---- | ----------- | | Func | () => Promise | The function that returns a promise. Can be an HTTP request, database query, or any async function. | | validResponses | Array | Array of valid response types. Success responses matching any of these types will trigger onSuccess. | | validErrors | Array | Array of valid error types. Errors matching any of these types will trigger onError. | onSuccess | (response: any) => void | Callback function executed when the response matches one of the valid response types. | | onError | (error: any) => void | allback function executed when the error matches one of the valid error types. | | onUnknown? | (unknown: any) => void | Optional callback for handling unknown responses that don’t match either success or error types. | | timeout? | number | Optional timeout in milliseconds for the operation (default is 5000 ms). |

Success and Error Type Matching

To simplify the validation, the library uses type inference based on the structure of the data. When you pass the validResponses or validErrors, the handler will check if the result matches any of the specified types. For example:

interface ValidResponse1 {
  id: number;
  title: string;
}

interface ValidResponse2 {
  name: string;
  age: number;
}

handler.handle({
  func: () => axiosInstance.get('/posts/1'),
  validResponses: [ValidResponse1, ValidResponse2], // Multiple success types
  validErrors: [ErrorInterface],  // Multiple error types
  onSuccess: (data) => {
    switch (data.constructor) {
      case ValidResponse1:
        console.log('Matched ValidResponse1:', data);****
        break;
      case ValidResponse2:
        console.log('Matched ValidResponse2:', data);
        break;
    }
  },
  onError: (error) => {
    console.error('Handled error:', error);
  },
  onUnknown: (unknown) => {
    console.warn('Unknown case detected:', unknown);
  },
});

License

MIT License.