Files
wws-functions/webhook/index.js
christiankrag 3fcebac27f Switch to ES module exports for wws runtime
- Replace module.exports with export default
- wws uses ES modules, not CommonJS
- Fixes 'module is not defined' error

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-15 06:01:10 +01:00

110 lines
3.0 KiB
JavaScript

// Webhook receiver for external integrations
// Path: /webhook
async function handler(request) {
const corsHeaders = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type, Authorization, X-Webhook-Secret',
'Content-Type': 'application/json'
}
if (request.method === 'OPTIONS') {
return new Response('', { headers: corsHeaders })
}
// GET request - return webhook info
if (request.method === 'GET') {
return new Response(JSON.stringify({
endpoint: '/webhook',
method: 'POST',
supported_sources: ['gitea', 'stripe', 'supabase', 'default'],
usage: 'POST /webhook?source=gitea with JSON body'
}, null, 2), {
headers: corsHeaders
})
}
// POST request - receive and forward webhook
if (request.method === 'POST') {
try {
const timestamp = new Date().toISOString()
// Parse request body
let payload
const contentType = request.headers.get('content-type') || ''
if (contentType.indexOf('application/json') !== -1) {
payload = await request.json()
} else {
payload = await request.text()
}
// Get source from query params
let source = 'default'
if (request.url && request.url.indexOf('?') !== -1) {
const queryString = request.url.split('?')[1]
if (queryString) {
const params = queryString.split('&')
for (let i = 0; i < params.length; i++) {
const pair = params[i].split('=')
if (pair[0] === 'source' && pair[1]) {
source = decodeURIComponent(pair[1])
break
}
}
}
}
// Forward to appropriate n8n workflow based on source
const webhookMap = {
'gitea': 'https://n8n.mylder.io/webhook/gitea-event',
'stripe': 'https://n8n.mylder.io/webhook/stripe-event',
'supabase': 'https://n8n.mylder.io/webhook/supabase-event',
'default': 'https://n8n.mylder.io/webhook/generic-event'
}
const targetUrl = webhookMap[source] || webhookMap['default']
// Forward to n8n (fire and forget)
fetch(targetUrl, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
source: source,
payload: payload,
received_at: timestamp
})
}).catch(function(err) {
console.error('Forward failed:', err)
})
return new Response(JSON.stringify({
received: true,
source: source,
timestamp: timestamp
}), {
headers: corsHeaders
})
} catch (error) {
return new Response(JSON.stringify({
received: false,
error: error.message || 'Parse error'
}), {
status: 400,
headers: corsHeaders
})
}
}
// Method not allowed
return new Response(JSON.stringify({ error: 'Method not allowed' }), {
status: 405,
headers: corsHeaders
})
}
// ES Module export for wws
export default handler