https://github.com/aragaoi/context-storage
Generic AsyncLocalStorage wrapper for context management
https://github.com/aragaoi/context-storage
async-local-storage context-manager generic-tool helper-tools npm-package request-context shared-context utility
Last synced: 5 months ago
JSON representation
Generic AsyncLocalStorage wrapper for context management
- Host: GitHub
- URL: https://github.com/aragaoi/context-storage
- Owner: aragaoi
- License: mit
- Created: 2025-08-25T20:39:17.000Z (10 months ago)
- Default Branch: main
- Last Pushed: 2025-09-02T20:05:58.000Z (9 months ago)
- Last Synced: 2025-09-22T10:26:22.754Z (9 months ago)
- Topics: async-local-storage, context-manager, generic-tool, helper-tools, npm-package, request-context, shared-context, utility
- Language: TypeScript
- Homepage:
- Size: 189 KB
- Stars: 0
- Watchers: 0
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- Changelog: CHANGELOG.md
- License: LICENSE
Awesome Lists containing this project
README
# @aragaoi/context-storage
[](https://github.com/seachegue/context-storage) [](https://www.npmjs.com/package/@aragaoi/context-storage)
> **Documentation**: This package is a wrapper around Node.js [AsyncLocalStorage](https://nodejs.org/download/release/v18.17.1/docs/api/async_context.html). For a detailed explanation of how AsyncLocalStorage works, see our [AsyncLocalStorage Guide](./ASYNC_STORAGE_GUIDE.md).
- ๐ **Type-safe**: Full TypeScript support with generics
- ๐ **Zero dependencies**: Only uses Node.js built-ins
- ๐งน **Automatic cleanup**: Context is automatically cleaned up after async operations
- ๐ฏ **Simple API**: Easy to use with minimal boilerplate
- ๐ **Async support**: Works seamlessly with async/await
## Installation
```bash
npm install context-storage
```
## Quick Start
### Basic Usage
```typescript
import { ContextStorage } from "context-storage";
// Create a context storage for user data
const userContext = new ContextStorage(() => ({
userId: "",
role: "guest"
}));
// Use context in your application
userContext.runWithContext(() => {
// Set user data
userContext.updateContext({ userId: "user-123", role: "admin" });
// Access context anywhere in this scope
const user = userContext.getContext();
console.log(user); // { userId: "user-123", role: "admin" }
});
```
### Request Context (Pre-configured)
```typescript
import { requestContextStorage } from "context-storage";
// Use the pre-configured request context
requestContextStorage.runWithContext(() => {
// Add user info to context
requestContextStorage.updateContext({
userId: "user-123",
tenantId: "tenant-456"
});
// Access request context anywhere
const context = requestContextStorage.getContext();
console.log(context.requestId); // Unique request ID
console.log(context.userId); // "user-123"
});
```
## API Reference
### ContextStorage
#### Constructor
```typescript
new ContextStorage(contextFactory: () => T, contextName?: string)
```
#### Methods
- `runWithContext(callback: () => T): T` - Run code within a context
- `getContext(): T | null` - Get current context (nullable)
- `getContextOrThrow(): T` - Get current context (throws if missing)
- `updateContext(partial: Partial): void` - Update current context
### RequestContext
Pre-configured context type for HTTP requests:
```typescript
type RequestContext = {
requestId: string;
userId?: string;
tenantId?: string;
startedAt: string;
startedAtTimestamp: number;
token?: string;
};
```
## Examples
### Express.js Middleware
```typescript
import { requestContextStorage } from "context-storage";
app.use((req, res, next) => {
requestContextStorage.runWithContext(() => {
// Add request data to context
requestContextStorage.updateContext({
userId: req.user?.id,
token: req.headers.authorization
});
next();
});
});
// In your route handlers
app.get("/api/data", (req, res) => {
const context = requestContextStorage.getContextOrThrow();
console.log(`Request ${context.requestId} from user ${context.userId}`);
// ... handle request
});
```
### Database Operations
```typescript
import { ContextStorage } from "context-storage";
const dbContext = new ContextStorage(() => ({
transactionId: "",
userId: ""
}));
async function createUser(userData: any) {
return dbContext.runWithContext(async () => {
dbContext.updateContext({
transactionId: generateId(),
userId: userData.id
});
// All database operations have access to context
await db.beginTransaction();
await db.insertUser(userData);
await db.logActivity("user_created");
await db.commit();
});
}
```
## Requirements
- Node.js 16.0.0 or higher
- TypeScript (recommended)
## License
MIT