@mappia/whook
v0.0.6
Published
A tiny, strongly-typed event handler system in TypeScript for building modular and extensible hook/event pipelines.
Readme
@mappia/whook
A tiny, strongly-typed event handler system in TypeScript for building modular and extensible hook/event pipelines.
✨ Features
- 🔒 Fully type-safe — handlers are scoped to their event type
- ⚙️ Composable — define and combine handlers easily
- ⏱ Async-ready — supports async handlers with Promise.allSettled
- 📦 Zero dependencies
📦 Installation
npm install @mappia/whook🧠 Concept
@mappia/whook allows you to define events with a discriminated union type, register event-specific handlers, and then combine them into a single dispatcher that can invoke all relevant handlers for an event.
🚀 Usage
- Define your event types
type MyEvents =
| { type: 'user.created'; id: string }
| { type: 'order.placed'; orderId: number };- Create the system
import { createEventHandlerSystem } from '@mappia/whook';
const { on, combineHandlers } = createEventHandlerSystem<MyEvents>();- Register handlers
const userCreated = on('user.created', async (event) => {
console.log('New user ID:', event.id);
});
const orderPlaced = on('order.placed', async (event) => {
console.log('Order ID:', event.orderId);
});const dispatch = combineHandlers(userCreated, orderPlaced);
await dispatch('user.created', { type: 'user.created', id: 'abc123' });
await dispatch('order.placed', { type: 'order.placed', orderId: 42 });🧩 Type Safety
If you try to register a handler for an unknown event type or handle the wrong payload, TypeScript will catch it:
// ❌ TypeScript error
on('unknown.event', async (e) => {});