Receive an inventory message
Deliver a shipment notice to a handler, inspect its JSON payload and close the application. This first example runs entirely in one process. Install @chojs/message using project setup.
1. Subscribe to a topic
Save the following as app.ts. The controller and method names in the decorators combine into the literal topic books.received. The handler checks the incoming data before using it.
import {
ChoMessage, type ChoMessageContext, Controller, Module, Subscribe,
} from "@chojs/message";
@Controller({ topic: "books" })
class Inventory {
@Subscribe("received")
receive(ctx: ChoMessageContext) {
const value = ctx.json<unknown>();
if (typeof value !== "object" || value === null ||
!("isbn" in value) || typeof value.isbn !== "string") {
throw new TypeError("Expected a string isbn");
}
console.log("Received " + value.isbn + " on " + ctx.topic);
}
}
@Module({ controllers: [Inventory] })
export class Library {}
export const createApp = () => ChoMessage.create(Library);2. Deliver a message
Save the entry point as main.ts. The key identifies the delivery in this example. The topic selects the handler.
import { createApp } from "./app.ts";
const app = await createApp();
try {
await app.handle("books.received", {
key: "copy-17",
value: JSON.stringify({ isbn: "9780140268867" }),
});
} finally {
await app.close();
}deno run main.tsnpx tsx main.tsbun run main.tsExpect Received 9780140268867 on books.received. The promise returned by handle resolves when the handler and its middleware finish.
3. Exercise a failure
Change value to '{"isbn":17}' and run the program again. The handler throws Expected a string isbn and handle rejects. The finally block releases the application in either case. Changing the topic to books.missing tests a different failure, because there is no subscription for that name.
Connect a broker
Once the handler works in memory, pass a linker to ChoMessage.create and call await app.start(). The linker subscribes to the compiled topics and forwards deliveries into the same handlers. For a Node.js deployment, follow the Kafka guide to configure retries and dead-letter handling.