Files
wws-functions/chat/index.js
christiankrag 97dbd958cc Fix chat endpoint - use text() instead of json()
- wws Response object may not have json() method
- Parse response manually with JSON.parse

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

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

81 lines
2.5 KiB
JavaScript

// Chat proxy - routes requests to n8n workflow
// Path: /chat
const handler = async (request) => {
if (request.method === 'OPTIONS') {
let response = new Response('')
response.headers.set('Access-Control-Allow-Origin', '*')
response.headers.set('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
response.headers.set('Access-Control-Allow-Headers', 'Content-Type, Authorization')
return response
}
if (request.method !== 'POST') {
let response = new Response(JSON.stringify({ error: 'Method not allowed' }))
response.headers.set('Content-Type', 'application/json')
response.headers.set('Access-Control-Allow-Origin', '*')
return response
}
try {
const body = await request.json()
const message = body.message
const project_id = body.project_id
const user_id = body.user_id
const provider = body.provider || 'zai'
if (!message) {
let response = new Response(JSON.stringify({ error: 'Message is required' }))
response.headers.set('Content-Type', 'application/json')
response.headers.set('Access-Control-Allow-Origin', '*')
return response
}
// Forward to n8n webhook
const n8nResponse = await fetch('https://n8n.mylder.io/webhook/chat', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
message: message,
project_id: project_id || null,
user_id: user_id || null,
provider: provider,
source: 'wws-proxy',
timestamp: new Date().toISOString()
})
})
// Use text() and parse manually (json() may not be available in wws)
const responseText = await n8nResponse.text()
let result
try {
result = JSON.parse(responseText)
} catch (e) {
result = { text: responseText }
}
let response = new Response(JSON.stringify({
success: true,
response: result.response || result,
provider: provider,
timestamp: new Date().toISOString()
}))
response.headers.set('Content-Type', 'application/json')
response.headers.set('Access-Control-Allow-Origin', '*')
return response
} catch (error) {
let response = new Response(JSON.stringify({
success: false,
error: error.message || 'Internal server error'
}))
response.headers.set('Content-Type', 'application/json')
response.headers.set('Access-Control-Allow-Origin', '*')
return response
}
}
addEventListener('fetch', event => {
return event.respondWith(handler(event.request))
})