-
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
refactor: move webhook logic to class
- Loading branch information
1 parent
9ce179f
commit b25a214
Showing
2 changed files
with
56 additions
and
17 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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}`); | ||
} | ||
}; | ||
} |