A port used to communicate with NATS, the cloud native messaging system.
NATS_URL
environment variable to connect to the NATS node.
// src/components.ts
await createNatsComponent({ config, logs })
You'd normally won't have to call this function, as that is taken care by the Lifecycle.run
method. But the method will:
- Attempt to establish a connection with the NATS node
- Emit a
connected
event if the connection is successful
Subscribe to a NATS topic
export async function setupTopics(globalContext: GlobalContext): Promise<void> {
const { nats } = globalContext.components
// Subscribe to the topic
const connectSubscription = nats.subscribe('peer.*.connect', (err, message) => {
if (err) {
logger.error(err)
return
}
// Process messages received for the topic
try {
// Extract information from the subject for the topic
// 'peer.837.connect' => '837'
const id = message.subject.split('.')[1]
// Parse the data from the message. Data is encoded as Uint8Array
const data = message.data
} catch (err: any) {
logger.error(`cannot process peer_connect message ${err.message}`)
}
}
})
}
Publish a message to a NATS topic
export async function setupTopics(globalContext: GlobalContext): Promise<void> {
const { nats } = globalContext.components
const peerId = '837'
const payload = ... // Uint8Array
// `payload` is optional
components.nats.publish(`peer.${peerId.connect`, payload)
}
Encode/Decode JSON messages using JSONCodec
. Any other codec that encodes to Uint8Array
can be used.
import { encodeJson, decodeJson } from '@well-known-components/nats-component'
const jsonMessage = { id: 1 }
// Encode
const encodedMessage = encodeJson(jsonMessage)
// Decode
const decodedMessage = decodeJson(encodedMessage)