nestjs-microservices-aws-iot
v0.0.8
Published
AWS IoT Client Wrapper for Nest.js Microservices
Downloads
14
Maintainers
Readme
nestjs-microservices-aws-iot
Usage Notice
This package was created to share internal code and may be used as-is. Please note that no guarantees are made regarding the functionality or suitability of the code in all environments.
Overview
This package provides a seamless wrapper for the AWS IoT SDK within Nest.js microservices, enabling easy integration with AWS IoT Core. With this, you can effortlessly publish and subscribe to MQTT topics using AWS IoT services in your Nest.js application.
Features
Note: This package is still under development. The initial release includes the following features:
- Publish messages to an MQTT topics
- Subscribe to an MQTT topics
- Simplified configuration through Nest.js dependency injection
Installation
# for npm
npm install nestjs-microservices-aws-iot
# for yarn
yarn add nestjs-microservices-aws-iot
# for pnpm
pnpm add nestjs-microservices-aws-iotUsage
Subscribing to an MQTT Topic
To subscribe to a topic, set up the microservice in your main.ts as follows:
import { AwsIotServer } from 'nestjs-microservices-aws-iot';
import type { AwsIotContext } from 'nestjs-microservices-aws-iot';
const app = await NestFactory.createMicroservice<MicroserviceOptions>(
AppModule,
{
strategy: new AwsIotServer({
hostname: '[your-iot].iot.[region].amazonaws.com',
certPath: './keys/cert.pem',
keyPath: './keys/private.key',
}),
},
);Then, in your controller, listen to incoming messages from the topic:
interface PayloadResponse {
hello: string;
}
...
@MessagePattern('awesomeTopic')
topic(@Payload() data: AwsIotPayload<PayloadResponse>, @Ctx() context: AwsIotContext<PayloadResponse>) {
console.log(data, context);
}
@MessagePattern('wildcardTopic/+/hello')
wildcard(@Payload() data: AwsIotPayload<PayloadResponse>, @Ctx() context: AwsIotContext<PayloadResponse>) {
console.log(data, context);
}
...Publishing a Message to an MQTT Topic
import { AwsIotClient } from 'nestjs-microservices-aws-iot';
export class AppService {
private client: AwsIotClient;
constructor() {
// Initialize the client
this.client = new AwsIotClient({
hostname: '[your-iot].iot.[region].amazonaws.com',
certPath: './keys/cert.pem',
keyPath: './keys/private.key',
});
}
public publishMessage() {
// Publish a message to the topic
this.client
.send('topic', {
message: 'Hello, World!',
})
.subscribe();
}
}Additional Resources
For more details on using Nest.js, refer to the official documentation: Nest.js Microservices Overview.
