- Add new ConsumerConfig to the ServiceProvider.
- Create a new Message
- Create a new RequestHandler for your new incoming message
- Create a new Consumer class, which extends the abstract Consumer class.
- Inject the new consumer into the Application class and call the consumer with the RabbitMQ connection.
- Testing the consumer
.provideValue("ExampleConsumerConfig", {
queue: "example_queue",
} as ConsumerConfig)
@Serializable() // <-- TS-jackson serializer
export default class ExamplePayload {
@JsonProperty("title")
readonly title?: string;
}
export default class ExampleMessage extends Message<ExamplePayload> {}
export default class ExampleRequestHandler implements RequestHandler {
public async handle(message: ConsumeMessage): Promise<void> {
const exampleMessage = deserialize(
message.content.toString(),
ExampleMessage
); // <-- TS-jackson deserializer
console.log(exampleMessage);
}
}
// register the service provider
const provider = new ServiceProvider().register();
// resolve the class by it's identifier
const logger = provider.resolve("Logger");
logger.info("Successfully injected the Logger");
export default class ExampleConsumer extends Consumer {
public static inject = [
"ExampleRequestHandler", // <-- The new RequestHandler
"ExampleConsumerConfig", // <-- The new ConsumerConfig
] as const;
public constructor(
private readonly requestHandler: RequestHandler,
protected readonly config: ConsumerConfig
) {
super(config);
}
public handler() {
return this.requestHandler.handle; // Just return the handle method
}
}
await this.exampleConsumer.consume(connection);
- Run
yarn fake
to send 10 fake message to theexample_queue
.