Overview
Add metadata to message patterns for documentation and versioning.
Features
- Message with metadata
- Event patterns
- Versioned messages
- Deprecated patterns
Installation
npx hanma add message --framework nest
Dependencies
@nestjs/microservices
Code
import { applyDecorators, SetMetadata } from "@nestjs/common";
import { MessagePattern, EventPattern } from "@nestjs/microservices";
export const MESSAGE_METADATA_KEY = "message_metadata";
export interface MessageMetadata {
name: string;
description?: string;
version?: string;
deprecated?: boolean;
}
/**
* Enhanced message pattern with metadata for documentation.
*
* Usage:
* @Message("user.create", { description: "Creates a new user" })
* async createUser(@Payload() data: CreateUserDto) {}
*/
export function Message(pattern: string, metadata?: Omit<MessageMetadata, "name">) {
return applyDecorators(
MessagePattern(pattern),
SetMetadata(MESSAGE_METADATA_KEY, { name: pattern, ...metadata })
);
}
/**
* Enhanced event pattern with metadata.
* Events are fire-and-forget (no response expected).
*
* Usage:
* @Event("user.created")
* async onUserCreated(@Payload() data: UserCreatedEvent) {}
*/
export function Event(pattern: string, metadata?: Omit<MessageMetadata, "name">) {
return applyDecorators(
EventPattern(pattern),
SetMetadata(MESSAGE_METADATA_KEY, { name: pattern, ...metadata })
);
}
/**
* Versioned message pattern.
*
* Usage:
* @VersionedMessage("user.create", "v2")
* async createUserV2(@Payload() data: CreateUserDtoV2) {}
*/
export function VersionedMessage(pattern: string, version: string) {
const versionedPattern = `${version}.${pattern}`;
return applyDecorators(
MessagePattern(versionedPattern),
SetMetadata(MESSAGE_METADATA_KEY, { name: pattern, version })
);
}
/**
* Mark a message handler as deprecated.
*/
export function DeprecatedMessage(pattern: string, replacement?: string) {
return applyDecorators(
MessagePattern(pattern),
SetMetadata(MESSAGE_METADATA_KEY, {
name: pattern,
deprecated: true,
description: replacement ? `Deprecated. Use ${replacement} instead.` : "Deprecated",
})
);
}
Usage
@Message('user.create', { description: 'Creates user' })
createUser(@Payload() data: CreateUserDto) {}
Dependencies
@nestjs/microservices
Frequently Asked Questions
How do I install Message Patterns?
Run the following command:
npx hanma add message --framework nestWhat dependencies are required?
This snippet requires: @nestjs/microservices. Make sure to install them before using the snippet.
How do I use this snippet?
Copy the code and paste it into your project. The snippet will be saved to
src/decorators/message.decorator.ts.Can I customize this snippet?
Yes! All snippets are copy-paste code that you own. Feel free to modify them to fit your needs.
Does this work with other frameworks?
This snippet is designed for the specific framework. Check the other framework pages for equivalent implementations.