API reference / @node-ts/bus-messages / defineCommand
Function: defineCommand()
function defineCommand<TName>(name, options?): <TData>() => MessageDefinition<DefinedMessage<TName, TData>, TData>;Defined in: packages/bus-messages/src/define-command.ts:29
Declares a command, an instruction sent to one handler, without writing a class. The definition creates commands from their fields, and is used anywhere a message class is: handlerFor, startedBy and when. The commands it creates are plain objects, with $name and $version added.
The name comes first and the fields second, so the name's literal type is inferred. Run bus generate-message-types (in @node-ts/bus-cli) to have Dates, Maps, Sets, bigints and classes in the fields restored when the command is received.
Type Parameters
| Type Parameter |
|---|
TName extends string |
Parameters
| Parameter | Type | Description |
|---|---|---|
name | TName | the $name of the command, which routes it, so make it unique |
options? | DefineMessageOptions | the $version of the command's contract |
Returns
a function that takes the type of the command's fields as its type argument, and returns the definition
<TData>() => MessageDefinition<DefinedMessage<TName, TData>, TData>
Example
export const PlaceOrder = defineCommand('@my-org/orders/place-order')<{
orderId: string
placedAt: Date
}>()
export type PlaceOrder = MessageOf<typeof PlaceOrder>
await bus.send(PlaceOrder({ orderId: '1', placedAt: new Date() }))
handlerFor(PlaceOrder, async placeOrder => placeOrder.placedAt.getTime())