Skip to content

Instantly share code, notes, and snippets.

@puuble
Created February 24, 2023 12:10
Show Gist options
  • Save puuble/b37b2fdf23a7557a4154835527a56618 to your computer and use it in GitHub Desktop.
Save puuble/b37b2fdf23a7557a4154835527a56618 to your computer and use it in GitHub Desktop.
worker
require("dotenv").config();
const axios = require("axios");
async function postData(url, res) {
try {
const options = {
url,
method: "POST",
headers: {"Content-Type": "application/json"},
data: res.body,
};
const axiosInstance = axios.create({});
const responses = await axiosInstance.request(options);
console.log(responses.map((response) => response.data));
} catch (error) {
console.error(error.message);
}
}
async function sendDataWithWebHook(url, result) {
try {
await postData(url, result);
} catch (error) {
console.error(error);
}
}
const {SQSClient, ReceiveMessageCommand, DeleteMessageCommand} = require("@aws-sdk/client-sqs");
class SQSWorker {
constructor(queueUrl) {
this.queueUrl = queueUrl;
this.sqs = new SQSClient({region: "eu-central-1"});
}
async start() {
console.log(`Started listening to queue ${this.queueUrl}`);
while (true) {
const command = new ReceiveMessageCommand({
QueueUrl: this.queueUrl,
WaitTimeSeconds: 20, // use long polling with a 20-second wait time
MaxNumberOfMessages: 1,
});
try {
const data = await this.sqs.send(command);
const messages = data.Messages;
if (messages) {
messages.forEach(async (message) => {
const messageBody = JSON.parse(message.Body);
if (messageBody.type == "sendWH") {
console.log("r", messageBody.recipients);
await sendDataWithWebHook(messageBody.recipients, messageBody.result);
const deleteCommand = new DeleteMessageCommand({
QueueUrl: this.queueUrl,
ReceiptHandle: message.ReceiptHandle,
});
await this.sqs.send(deleteCommand);
}
//console.log("d:", messageBody);
});
}
} catch (error) {
console.log(`Error receiving message: ${error}`);
}
}
}
}
const worker = new SQSWorker("https://sqs.eu-central-1.amazonaws.com/532527760149/posentegraQu");
worker.start().catch((error) => console.log(`Error starting worker: ${error}`));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment