gc-nats
A TypeScript Node.js wrapper service for the NATS streaming server based on stan.js client.
Publishing messages
import "reflect-metadata";
import { JsonController, Get, Res } from 'routing-controllers';
import { Inject, Service } from 'typedi';
import { ResponseUtil, logger } from '@app/utils';
import { NatsService } from '@buzzkey/gc-nats';
@JsonController('/v1')
@Service()
export class PingController {
@Inject()
public natsService: NatsService;
@Get('/ping')
async ping(@Res() res: any) {
const channel: string = "ping";
const message: any = {
info: "testing ping"
};
const messageId: string = await this.natsService.publish(channel, message);
logger.debug(`published message: ${messageId}`);
return ResponseUtil.ok({ message: 'Ping Successful' }, res);
}
}
Subscribing to messages from a channel/subject
import { logger } from '@app/utils';
import { natsConnectionConfigs } from '@app/config/nats.config';
import { Worker } from '@buzzkey/gc-nats';
const subject = "ping";
@Worker(natsConnectionConfigs, subject)
export class PingWorker {
channel: string = subject;
public async messageReceived (message: string) {
logger.debug('Ping successful. worker processing message: ', message);
}
}