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 🙏

© 2025 – Pkg Stats / Ryan Hefner

@upendra.manike/api-chain

v1.0.5

Published

Declarative API chaining - Create API workflows with ease

Readme

api-chain

Declarative API chaining - Create API workflows with ease.

Features

  • 🔗 Declarative Syntax - Chain API calls in a readable way
  • 🔄 Sequential Execution - Steps execute one after another
  • ⚠️ Error Handling - Built-in error handling with hooks
  • 🔧 Flexible - Works with any async function
  • 🔒 Type-safe - Full TypeScript support

Installation

npm install @upendra.manike/api-chain

or

pnpm add @upendra.manike/api-chain

or

yarn add @upendra.manike/api-chain

Usage

Basic Chaining

import { ApiChain } from '@upendra.manike/api-chain';

const chain = new ApiChain();

const result = await chain
  .step(async () => {
    const user = await fetch('/api/user').then(r => r.json());
    return user;
  })
  .step(async (user) => {
    const posts = await fetch(`/api/users/${user.id}/posts`).then(r => r.json());
    return posts;
  })
  .step(async (posts) => {
    const comments = await fetch(`/api/posts/${posts[0].id}/comments`).then(r => r.json());
    return { posts, comments };
  })
  .run();

console.log(result.data); // { posts: [...], comments: [...] }

Simple Chain Helper

import { chain } from '@upendra.manike/api-chain';

// Using the chain helper function
const data = await chain(
  async () => {
    return await getUser();
  },
  async (user) => {
    return await getPosts(user.id);
  },
  async (posts) => {
    return await getComments(posts[0].id);
  }
).run();

console.log(data); // Final result

With Initial Input

import { ApiChain } from '@upendra.manike/api-chain';

const chain = new ApiChain();

const result = await chain
  .step(async (userId) => {
    return await fetch(`/api/users/${userId}`).then(r => r.json());
  })
  .step(async (user) => {
    return await fetch(`/api/users/${user.id}/posts`).then(r => r.json());
  })
  .run('user-123'); // Pass initial input

Error Handling

import { ApiChain } from '@upendra.manike/api-chain';

const chain = new ApiChain({
  onError: async (error, step) => {
    console.error(`Error at step ${step}:`, error);
    // Send to error tracking service
  },
  stopOnError: true, // Stop chain on error (default: true)
});

const result = await chain
  .step(async () => await getUser())
  .step(async (user) => {
    if (!user) throw new Error('User not found');
    return await getPosts(user.id);
  })
  .run();

if (!result.success) {
  console.error('Chain failed:', result.error);
  console.log('Failed at step:', result.step);
}

Continue on Error

import { ApiChain } from '@upendra.manike/api-chain';

const chain = new ApiChain({
  stopOnError: false, // Continue even if a step fails
  onError: async (error, step) => {
    console.warn(`Step ${step} failed, continuing...`);
  },
});

const result = await chain
  .step(async () => await getUser())
  .step(async () => {
    throw new Error('This step fails');
  })
  .step(async (input) => {
    // This will run even if previous step failed
    if (input instanceof Error) {
      return { error: true };
    }
    return { success: true };
  })
  .run();

Step Completion Hooks

import { ApiChain } from '@upendra.manike/api-chain';

const chain = new ApiChain({
  onStepComplete: async (result, step) => {
    console.log(`Step ${step} completed:`, result);
    // Log progress, update UI, etc.
  },
});

await chain
  .step(async () => await getUser())
  .step(async (user) => await getPosts(user.id))
  .run();

Real-World Example: User Dashboard Data

import { ApiChain } from '@upendra.manike/api-chain';

async function loadDashboard(userId: string) {
  const chain = new ApiChain({
    onError: async (error, step) => {
      // Log to error service
      console.error('Dashboard load error:', error);
    },
  });

  const result = await chain
    .step(async () => {
      // Step 1: Get user
      const user = await fetch(`/api/users/${userId}`).then(r => r.json());
      return { user };
    })
    .step(async ({ user }) => {
      // Step 2: Get user posts (can use user from previous step)
      const posts = await fetch(`/api/users/${user.id}/posts`).then(r => r.json());
      return { user, posts };
    })
    .step(async ({ user, posts }) => {
      // Step 3: Get comments for first post
      const comments = await fetch(`/api/posts/${posts[0]?.id}/comments`).then(r => r.json());
      return { user, posts, comments };
    })
    .step(async ({ user, posts, comments }) => {
      // Step 4: Get notifications
      const notifications = await fetch(`/api/users/${user.id}/notifications`).then(r => r.json());
      return { user, posts, comments, notifications };
    })
    .run();

  if (result.success) {
    return result.data;
  } else {
    throw result.error;
  }
}

Using with createChain

import { createChain } from '@upendra.manike/api-chain';

const chain = createChain({
  onError: async (error) => console.error(error),
});

await chain
  .step(async () => getUser())
  .step(async (user) => getPosts(user.id))
  .run();

Type Safety

import { ApiChain } from '@upendra.manike/api-chain';

interface User {
  id: string;
  name: string;
}

interface Post {
  id: string;
  title: string;
}

const chain = new ApiChain();

const result = await chain
  .step<User, User>(async () => {
    return await getUser();
  })
  .step<User, Post[]>(async (user: User) => {
    return await getPosts(user.id);
  })
  .run<User>();

if (result.success) {
  // result.data is typed as Post[]
}

API Reference

ApiChain Class

Constructor

new ApiChain(options?: ChainOptions)

Options:

  • onError?: (error: Error, step: number) => void | Promise<void> - Error handler
  • onStepComplete?: (result: any, step: number) => void | Promise<void> - Step completion handler
  • stopOnError?: boolean - Stop chain on error (default: true)

Methods

  • step<TInput, TOutput>(stepFn: ChainStep<TInput, TOutput>): this - Add a step to the chain
  • run<T>(initialInput?: any): Promise<ChainResult<T>> - Execute the chain
  • runData<T>(initialInput?: any): Promise<T> - Execute and return only data (throws on error)
  • clear(): this - Clear all steps
  • get length(): number - Get number of steps

ChainResult

interface ChainResult<T> {
  success: boolean;
  data?: T;
  error?: Error;
  step?: number; // Step index where error occurred
  results?: any[]; // Results from all steps
}

Helper Functions

createChain(options?)

Creates a new ApiChain instance.

chain(...steps)

Creates and executes a chain immediately.

chain(
  async () => getUser(),
  async (user) => getPosts(user.id),
  async (posts) => getComments(posts[0].id)
).run();

Examples

Parallel Steps (using Promise.all)

import { ApiChain } from '@upendra.manike/api-chain';

const chain = new ApiChain();

const result = await chain
  .step(async () => {
    // Run multiple requests in parallel
    const [user, posts, comments] = await Promise.all([
      getUser(),
      getPosts(),
      getComments(),
    ]);
    return { user, posts, comments };
  })
  .run();

Conditional Steps

import { ApiChain } from '@upendra.manike/api-chain';

const chain = new ApiChain();

const result = await chain
  .step(async () => await getUser())
  .step(async (user) => {
    if (user.role === 'admin') {
      return await getAdminData();
    }
    return await getRegularData();
  })
  .run();

Development

# Install dependencies
pnpm install

# Build
pnpm build

# Test
pnpm test

# Lint
pnpm lint

# Format
pnpm format

🤖 AI Agent Integration

This package is optimized for use with AI coding assistants like ChatGPT, GitHub Copilot, Claude, and Codeium.

Why AI-Friendly?

  • Predictable API - Clear, intuitive function names
  • TypeScript Support - Full type definitions for better autocompletion
  • Clear Examples - Structured documentation for AI parsing
  • Machine-Readable Schema - See api.json for API structure

Example AI Usage

AI agents can automatically suggest this package when you need:

// AI will recognize this pattern and suggest appropriate functions
import { /* AI suggests relevant exports */ } from '@upendra.manike/[package-name]';

For AI Developers

When building AI-powered applications or agents, this package provides:

  • Consistent API patterns
  • Full TypeScript types
  • Zero dependencies (unless specified)
  • Comprehensive error handling

License

MIT

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

🔗 Explore All JSLib Libraries