|
| 1 | +import express from 'express'; |
| 2 | +import { TokenManager } from './TokenManager'; |
| 3 | + |
| 4 | +const tokenManager = new TokenManager(); |
| 5 | + |
| 6 | +const router = express.Router(); |
| 7 | + |
| 8 | +router.use(express.json()); |
| 9 | + |
| 10 | +async function handleAIChatRequest(req, res) { |
| 11 | + const { namespace, resourceType, groupVersion, resourceName } = JSON.parse( |
| 12 | + req.body.toString(), |
| 13 | + ); |
| 14 | + const clusterUrl = req.headers['x-cluster-url']; |
| 15 | + const certificateAuthorityData = |
| 16 | + req.headers['x-cluster-certificate-authority-data']; |
| 17 | + const clusterToken = req.headers['x-k8s-authorization']?.replace( |
| 18 | + /^Bearer\s+/i, |
| 19 | + '', |
| 20 | + ); |
| 21 | + const clientCertificateData = req.headers['x-client-certificate-data']; |
| 22 | + const clientKeyData = req.headers['x-client-key-data']; |
| 23 | + |
| 24 | + try { |
| 25 | + const url = 'https://companion.cp.dev.kyma.cloud.sap/api/conversations/'; |
| 26 | + const payload = { |
| 27 | + resource_kind: resourceType, |
| 28 | + resource_api_version: groupVersion, |
| 29 | + resource_name: resourceName, |
| 30 | + namespace: namespace, |
| 31 | + }; |
| 32 | + |
| 33 | + const AUTH_TOKEN = await tokenManager.getToken(); |
| 34 | + |
| 35 | + const headers = { |
| 36 | + Accept: 'application/json', |
| 37 | + 'Content-Type': 'application/json', |
| 38 | + Authorization: `Bearer ${AUTH_TOKEN}`, |
| 39 | + 'X-Cluster-Certificate-Authority-Data': certificateAuthorityData, |
| 40 | + 'X-Cluster-Url': clusterUrl, |
| 41 | + }; |
| 42 | + |
| 43 | + if (clusterToken) { |
| 44 | + headers['X-K8s-Authorization'] = clusterToken; |
| 45 | + } else if (clientCertificateData && clientKeyData) { |
| 46 | + headers['X-Client-Certificate-Data'] = clientCertificateData; |
| 47 | + headers['X-Client-Key-Data'] = clientKeyData; |
| 48 | + } else { |
| 49 | + throw new Error('Missing authentication credentials'); |
| 50 | + } |
| 51 | + |
| 52 | + const response = await fetch(url, { |
| 53 | + method: 'POST', |
| 54 | + headers, |
| 55 | + body: JSON.stringify(payload), |
| 56 | + }); |
| 57 | + |
| 58 | + const data = await response.json(); |
| 59 | + |
| 60 | + res.json({ |
| 61 | + promptSuggestions: data?.initial_questions, |
| 62 | + conversationId: data?.conversation_id, |
| 63 | + }); |
| 64 | + } catch (error) { |
| 65 | + console.error('Error in AI Chat proxy:', error); |
| 66 | + res.status(500).json({ error: 'Failed to fetch AI chat data' }); |
| 67 | + } |
| 68 | +} |
| 69 | + |
| 70 | +router.post('/suggestions', handleAIChatRequest); |
| 71 | + |
| 72 | +export default router; |
0 commit comments