Skip to content

Instantly share code, notes, and snippets.

@wemakefuture
Last active November 15, 2021 23:54
Show Gist options
  • Save wemakefuture/31a5a4f08c5ba25f875ef64fbc69e4cf to your computer and use it in GitHub Desktop.
Save wemakefuture/31a5a4f08c5ba25f875ef64fbc69e4cf to your computer and use it in GitHub Desktop.
MDM Integromat Webhook
const DOMAIN = 'hook.wemakefuture.com'; // path to be proxied
const ORIGIN = 'hook.integromat.com'; // where to fetch content from
addEventListener('fetch', event => {
var url = new URL(event.request.url);
if (url.pathname != "") {
console.log(url.pathname)
event.respondWith(handleRequest(event, url))
}
})
async function handleRequest(event, url) {
const text = await event.request.clone().text()
// Change URL from public URL to use the origin URL
var originUrl = url.toString().replace(
'https://' + DOMAIN + url.pathname,
'https://' + ORIGIN + url.pathname
);
let mongoBody = { "timestamp": Date.now() }
const mongoWebhook = "SOMEMONGODOMAIN"
try {
const json = JSON.parse(text)
mongoBody["originalBody"] = json;
mongoBody["isBodyJson"] = true;
let originConfig = {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(json)
}
try {
let originResult = await fetch(originUrl, originConfig)
mongoBody["success"] = originResult.ok;
mongoBody["result"] = originResult
return originResult
}
catch (err) {
mongoBody["success"] = false;
return (err.message)
}
finally {
// Write the data to the MongoDB
// will be exectuted even after the return statements
let mongoConfig = {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(mongoBody)
}
let databaseResult = await fetch(mongoWebhook, mongoConfig)
}
}
catch (e) {
// if no valid JSON was posted to the webhook
let textResponse = await fetch(originUrl, {
method: 'POST',
body: text
});
mongoBody["originalBody"] = text;
mongoBody["isBodyJson"] = false;
mongoBody["success"] = textResponse.ok;
mongoBody["result"] = textResponse;
let mongoConfig = {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(mongoBody)
}
let databaseResult = await fetch(mongoWebhook, mongoConfig)
return textResponse
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment