Skip to content

Commit

Permalink
refactor: move webhook logic to class
Browse files Browse the repository at this point in the history
  • Loading branch information
Th3S4mur41 committed Sep 27, 2024
1 parent 9ce179f commit b25a214
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 17 deletions.
28 changes: 11 additions & 17 deletions src/index.mjs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { Device } from "./homewizard/device.mjs";
import { Webhook } from "./webhooks/webhook.mjs";

/**
* energyid-homewizard-connector
Expand Down Expand Up @@ -61,6 +62,8 @@ const typeMap = [
];

class Reading {
remoteName;

constructor(type, date, value) {
this.remoteId = type[1].id;
this.remoteName = type[1].name;
Expand Down Expand Up @@ -96,28 +99,19 @@ const setReadings = (data) => {

const sendReadings = (readings, dryRun) => {
console.log(dryRun ? "Printing readings to console..." : "Sending readings to EnergyId Webhook...");
const webhook = new Webhook("EnergyId", energyid_hook, "POST");

for (const reading of readings) {
if (dryRun) {
console.log(`Reading to send: ${reading.json()}`);
return;
}
fetch(energyid_hook, {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
body: reading.json(),
})
.then((response) => {
if (!response.ok) {
throw new Error(`Error sending reading: ${reading.json()}`);
}
console.log(`Sending reading: ${reading.json()}`);
})
.catch((e) => {
console.error(e.message);
});

try {
webhook.send(reading.json());
} catch (e) {
// console.error(e.message);
}
}
};

Expand Down
45 changes: 45 additions & 0 deletions src/webhooks/webhook.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
/**
* Webhook class
*/

const METHODS = new Set(["GET", "POST", "PUT", "PATCH", "DELETE"]);

export class Webhook {
#name = "";
#url = "";
#method = ""; /**
* Create a new Webhook instance
* @param {*} name - Set a name for the webhook
* @param {*} url - Set the URL of the webhook
* @param {*} method - [optional] Set the method to use for the webhook (Default: GET)
*/
constructor(name, url, method = "GET") {
this.#name = name;
this.#url = url;
this.#method = METHODS.has(method.toUpperCase()) ? method.toUpperCase() : "GET";
}

send = async (data = "") => {
const jsonData = JSON.parse(data);
console.log(`[${this.#name}] Sending ${jsonData.remoteName || "data"}...`);

try {
const response = await fetch(this.#url, {
method: this.#method,
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
body: data,
});

if (!response.ok) {
throw new Error();
}

console.log(`[${this.#name}] Sent reading: ${reading.json()}`);
} catch (e) {
console.error(`[${this.#name}] Error sending reading: ${data}`);
}
};
}

0 comments on commit b25a214

Please sign in to comment.