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

node-application-context

v1.1.3

Published

This library simplifies the way you manage and pass data across deeply nested function calls by introducing a shared execution context. With this library, you no longer need to manually pass parameters between functions. Instead, you set context data at t

Downloads

9

Readme

AppContext Library

The AppContext library simplifies managing execution context across asynchronous function calls in Node.js applications. This eliminates the need to pass parameters through deeply nested function calls by using the AsyncLocalStorage API. With AppContext, you can store and access context-specific data (e.g., user authentication details, request IDs) throughout your application logic without passing them explicitly.

Installation

Install the library via npm:

npm install node-application-context

You'll also need to install the uuid package as a peer dependency:

npm install uuid

Usage

Basic Setup

To use the AppContext library, define your context data type, initialize the context, and start using it within asynchronous functions.

import AppContext from 'node-application-context';

// Define your context data structure
type MyContextType = {
  userId: string;
  requestId: string;
};

// Initialize the context
const appContext = AppContext.context<MyContextType>();

// Start a new context and run a function within it
appContext.startContext(async () => {
  // Set context data
  appContext.set({ userId: '12345', requestId: 'req-67890' });

  // Retrieve context data later in the same execution context
  const contextData = appContext.get();
  console.log(contextData); // { userId: '12345', requestId: 'req-67890' }
});

API Reference

startContext<PromiseType>(fn: () => void | Promise<PromiseType>)

Starts a new execution context, running the provided function within this context. The function can be synchronous or asynchronous.

  • Returns: Promise<PromiseType>
appContext.startContext<Promise<void>>(() => {
  // Set and use context data
  appContext.set({ userId: '12345' });
});

get(): Partial<ContextDataType>

Retrieves the context data associated with the current execution context. Throws an error if no context is found.

  • Returns: Partial<ContextDataType>
const contextData = appContext.get();

set(contextData: Partial<ContextDataType>)

Sets or updates the context data for the current execution context.

appContext.set({ userId: '67890' });

Example Use Case

Vanila nodeJS

The AppContext library is particularly useful in scenarios where you need to manage shared context in applications with complex asynchronous workflows, such as:

  • Request handling in an API server
  • Managing user sessions or transaction data across multiple layers
  • Storing request-specific data like tracking IDs or logging information
import AppContext from 'node-application-context';

type RequestContext = {
  requestId: string;
  userId: string;
};

const requestContext = AppContext.context<RequestContext>();

async function handleRequest() {
  await requestContext.startContext(async () => {
    requestContext.set({ requestId: 'abc123', userId: 'user456' });
    
    const context = requestContext.get();
    console.log(`Request ID: ${context.requestId}, User ID: ${context.userId}`);
  });
}

handleRequest();

Express

import express, { Request, Response } from 'express';
import AppContext, { expressAppContext, getExpressContext, setExpressContext, ExpressRequestContext } from 'node-application-context';

const app = express();
interface ContextData {
  user: UserData
}
// Pre-request function to be executed before each request is handled
const preRequestFn = async (req: Request, res?: Response) => {
  console.log('Pre-request function is called!');
  const userData = await someRepo.getUser(req.session.userId);
  setExpressContext({user: userData});
};

// Apply the AppContext middleware to handle context for each request
app.use(expressAppContext<ContextData>(preRequestFn));

// Example route
app.get('/user', (req: Request, res: Response) => {
  // Retrieve the current context, including request-specific data
  const context = AppContext.context<ExpressRequestContext<ContextData>>();

  // Respond with the user ID from the context
  res.json({
    message: 'Hello, User!',
    userId: context.user,
  });
});

// Start the server
app.listen(3000, () => {
  console.log('Server is running on http://localhost:3000');
});

fastify

import Fastify from 'fastify';
import { registerFastifyAppContext, getFastifyContext, setFastifyContext } from 'node-application-context';

const fastify = Fastify();

// Pre-request function to be executed before each request
const preRequestFn = (req: IncomingMessage) => {
  console.log('Pre-request function called for Fastify!');
};

// Register the AppContext middleware
registerFastifyAppContext(fastify, preRequestFn);

fastify.get('/user', async (request, reply) => {
  // Get the current Fastify context
  const context = getFastifyContext<{ userId: string }>();

  // Set some data in the context
  setFastifyContext({ userId: 'user123' });

  // Send a response with the context data
  return {
    message: 'Hello from Fastify!',
    userId: context.userId,
  };
});

// Start the server
fastify.listen({ port: 3000 }, (err, address) => {
  if (err) throw err;
  console.log(`Server running at ${address}`);
});

License

This project is licensed under the MIT License. See the LICENSE file for details.