@tsdiapi/events
v0.4.0
Published
Event handling plugin for TSDIAPI-Server with TypeDI integration and type-safe decorators.
Downloads
76
Maintainers
Readme
TSDIAPI-Events: Event Handling Plugin for TSDIAPI-Server
The TSDIAPI-Events plugin adds robust, scalable event management to TSDIAPI-Server. Built with mitt and TypeDI, it allows event-driven communication through TypeScript decorators, ensuring clean and modular code.
Features
- Event Decorators: Use
@On(event)to register event listeners. - Dispatch Events: Trigger events with
dispatchEvent(). - Type Safety: Define events with strict TypeScript types for payloads.
- Integration: Works with the TSDIAPI-Server lifecycle and dependency injection system.
- File Autoloading: Supports automatic loading of event files with glob patterns.
Installation
Install via NPM or CLI:
npm install @tsdiapi/eventsor using the CLI:
tsdiapi plugins add eventsCode Generation
| Name | Description |
| ------ | ---------------------------------------------------- |
| base | Create a new event file with a basic event listener. |
The TSDIAPI-Events plugin includes an event generator to streamline event creation. Use the tsdiapi CLI command to generate event files automatically:
tsdiapi generate eventsExample Usage
Define and Handle Events
import { On, dispatchEvent } from "@tsdiapi/events";
import { Service } from "typedi";
export enum EventType {
onNewUser = "onNewUser",
onAccountCreated = "onAccountCreated",
}
export interface EventPayloads {
[EventType.onNewUser]: { userId: string; name: string };
[EventType.onAccountCreated]: { accountId: string };
}
@Service()
export class EventListener {
@On(EventType.onNewUser)
public handleNewUser(payload: EventPayloads[EventType.onNewUser]) {
console.log("New user:", payload.name);
}
}
// Dispatch an event
dispatchEvent(EventType.onNewUser, { userId: "123", name: "John Doe" });Plugin Setup
Register the plugin in your createApp function:
import { createApp } from "@tsdiapi/server";
import TSDIAPIEventsPlugin from "@tsdiapi/events";
createApp({
plugins: [TSDIAPIEventsPlugin()],
});Summary
With TSDIAPI-Events, you can build scalable, event-driven APIs with minimal boilerplate. It integrates seamlessly with the TSDIAPI ecosystem, enabling better modularity, maintainability, and type-safe communication between components.
For more information, visit the TSDIAPI-Server GitHub.
