Part of the alepha package. Import from alepha/topic.
npm install alepha
Generic interface for pub/sub messaging. Gives you the ability to create topics and subscribers. This module provides only a memory implementation of the topic provider.
Primitives are functions that define and configure various aspects of your application. They follow the convention of starting with $ and return configured primitive instances.
For more details, see the Primitives documentation.
Creates a subscriber primitive to listen for messages from a specific topic.
Provides a dedicated message subscriber that connects to a topic and processes messages with custom handler logic, enabling scalable pub/sub architectures where multiple subscribers can react to the same events independently.
Key Features
Common Use Cases
1class UserActivityService { 2 userEvents = $topic({ 3 name: "user-activity", 4 schema: { 5 payload: t.object({ 6 userId: t.text(), 7 action: t.enum(["login", "logout", "purchase"]), 8 timestamp: t.number() 9 })10 }11 });12 13 activityLogger = $subscriber({14 topic: this.userEvents,15 handler: async (message) => {16 const { userId, action, timestamp } = message.payload;17 await this.auditLogger.log({18 userId,19 action,20 timestamp21 });22 }23 });24 25 async trackUserLogin(userId: string) {26 await this.userEvents.publish({27 userId,28 action: "login",29 timestamp: Date.now()30 });31 }32}
Creates a topic primitive for publish/subscribe messaging and event-driven architecture.
Enables decoupled communication through a pub/sub pattern where publishers send messages and multiple subscribers receive them. Supports type-safe messages, real-time delivery, event filtering, and pluggable backends (memory, Redis, custom providers).
Use Cases: User notifications, real-time chat, event broadcasting, microservice communication
1class NotificationService { 2 userActivity = $topic({ 3 name: "user-activity", 4 schema: { 5 payload: t.object({ 6 userId: t.text(), 7 action: t.enum(["login", "logout", "purchase"]), 8 timestamp: t.number() 9 })10 },11 handler: async (message) => {12 console.log(`User ${message.payload.userId}: ${message.payload.action}`);13 }14 });15 16 async trackLogin(userId: string) {17 await this.userActivity.publish({ userId, action: "login", timestamp: Date.now() });18 }19 20 async subscribeToEvents() {21 await this.userActivity.subscribe(async (message) => {22 // Additional subscriber logic23 });24 }25}