包详细信息

@breadstone/ziegel-platform-messaging

RueDeRennes971MIT0.0.9

Includes a event aggregator for publish and subcribe global events. (aka PubSubEvent, Mediator)

自述文件

@breadstone/ziegel-platform-messaging

MIT License TypeScript npm

Event aggregation and messaging patterns for the ziegel platform. Provides publish-subscribe events, event aggregators, and RxJS integration for decoupled communication between components.

Messaging: Event-driven architecture with pub/sub patterns, event aggregation, and reactive messaging for loosely coupled applications.

🚀 Overview

@breadstone/ziegel-platform-messaging provides:

  • Event Aggregator: Centralized event publishing and subscription management
  • Publish-Subscribe Events: Decoupled communication through pub/sub patterns
  • Subscription Management: Token-based subscription lifecycle management
  • RxJS Integration: Reactive extensions for event streams
  • Event Decorators: Decorator-based event configuration
  • Type-Safe Events: Strongly typed event handling and publishing

📦 Installation

npm install @breadstone/ziegel-platform-messaging
# or
yarn add @breadstone/ziegel-platform-messaging

🧩 Features & Usage Examples

Event Aggregator

import { EventAggregator, IEventAggregator, PubSubEvent } from '@breadstone/ziegel-platform-messaging';

// Create custom events
class UserLoggedInEvent extends PubSubEvent<{ userId: string; timestamp: Date }> {}

const eventAggregator = new EventAggregator();

// Subscribe to events
const subscription = eventAggregator.getEvent(UserLoggedInEvent).subscribe(payload => {
  console.log(`User ${payload.userId} logged in at ${payload.timestamp}`);
});

// Publish events
eventAggregator.getEvent(UserLoggedInEvent).publish({
  userId: '12345',
  timestamp: new Date()
});

Event Decorators

import { Event } from '@breadstone/ziegel-platform-messaging';

class UserService {
  @Event('UserCreated')
  createUser(userData: any) {
    // Method implementation
    return userData;
  }

  @Event('UserUpdated')
  updateUser(userId: string, updateData: any) {
    // Method implementation
    return { userId, ...updateData };
  }
}

Subscription Management

import {
  EventAggregator,
  SubscriptionToken,
  EventSubscription,
  IEventSubscription
} from '@breadstone/ziegel-platform-messaging';

const eventAggregator = new EventAggregator();

// Create subscription with token
const token = new SubscriptionToken();
const subscription: IEventSubscription = new EventSubscription(
  eventAggregator.getEvent(UserLoggedInEvent),
  payload => console.log('User action:', payload),
  token
);

// Unsubscribe using token
subscription.unsubscribe();

RxJS Integration

import { fromPubSubEvent, pubSub, pubSubEvent } from '@breadstone/ziegel-platform-messaging';
import { map, filter } from 'rxjs/operators';

// Convert pub/sub events to observables
const userEvents$ = fromPubSubEvent(eventAggregator.getEvent(UserLoggedInEvent));

// Use RxJS operators
const recentLogins$ = userEvents$.pipe(
  filter(payload => {
    const now = new Date();
    const loginTime = payload.timestamp;
    return (now.getTime() - loginTime.getTime()) < 60000; // Last minute
  }),
  map(payload => payload.userId)
);

recentLogins$.subscribe(userId => {
  console.log(`Recent login: ${userId}`);
});

// Alternative syntax
const userEventStream$ = pubSub(eventAggregator.getEvent(UserLoggedInEvent));
const userEventObservable$ = pubSubEvent(eventAggregator.getEvent(UserLoggedInEvent));

Pub/Sub Event Pattern

import { PubSubEvent } from '@breadstone/ziegel-platform-messaging';

// Define strongly typed events
interface OrderCreatedPayload {
  orderId: string;
  customerId: string;
  amount: number;
}

class OrderCreatedEvent extends PubSubEvent<OrderCreatedPayload> {}

// Use in services
class OrderService {
  constructor(private eventAggregator: IEventAggregator) {}

  createOrder(orderData: any): void {
    // Create order logic...

    // Publish event
    this.eventAggregator.getEvent(OrderCreatedEvent).publish({
      orderId: orderData.id,
      customerId: orderData.customerId,
      amount: orderData.total
    });
  }
}

class NotificationService {
  constructor(private eventAggregator: IEventAggregator) {
    // Subscribe to order events
    this.eventAggregator.getEvent(OrderCreatedEvent).subscribe(payload => {
      this.sendOrderConfirmation(payload.customerId, payload.orderId);
    });
  }

  private sendOrderConfirmation(customerId: string, orderId: string): void {
    // Send notification logic...
  }
}

class CreateUserHandler implements CommandHandler<CreateUserCommand> { async handle(command: CreateUserCommand): Promise<void> { // Handle user creation } }

const commandBus = new CommandBus(); commandBus.register('CreateUser', new CreateUserHandler()); await commandBus.send(new CreateUserCommand('John', 'john@example.com'));


### Message Queue

```typescript
import { MessageQueue, QueueMessage } from '@breadstone/ziegel-platform-messaging';

const queue = new MessageQueue('email-queue');

// Add message to queue
await queue.enqueue({
  id: 'msg-123',
  payload: { to: 'user@example.com', subject: 'Welcome' },
  timestamp: new Date()
});

// Process messages
await queue.process(async (message) => {
  // Send email
  console.log(`Sending email to ${message.payload.to}`);
});

📚 Package import points

import {
    // Message Bus
    MessageBus,
    IMessage,
    MessageHandler,

    // Event Bus
    EventBus,
    DomainEvent,
    EventHandler,

    // Command Bus
    CommandBus,
    Command,
    CommandHandler,

    // Message Queue
    MessageQueue,
    QueueMessage,

    // Integration
    MessageRouter,
    MessageFilter
} from '@breadstone/ziegel-platform-messaging';

📚 API Documentation

For detailed API documentation, visit: API Docs

Related Packages

  • @breadstone/ziegel-platform: Core platform services
  • @breadstone/ziegel-rx: Reactive programming patterns
  • @breadstone/ziegel-core: Foundation utilities

License

MIT

Issues

Please report bugs and feature requests in the Issue Tracker


Part of the ziegel Enterprise TypeScript Framework