diff --git a/components/email.tsx b/components/email.tsx index 5e49416..217a390 100644 --- a/components/email.tsx +++ b/components/email.tsx @@ -51,36 +51,56 @@ export function Email() { throw new Error(errorData.error || 'Failed to fetch emails'); } - // Get the response data - const data = await response.json(); - console.log('Received data:', data); + const rawText = await response.text(); + console.log('Raw API Response:', rawText); - // Check if data has the expected structure - if (!data || !Array.isArray(data.emails)) { - console.error('Invalid response format:', data); - throw new Error('Invalid response format: no emails array found'); + let data; + try { + data = JSON.parse(rawText); + console.log('Parsed API Response:', data); + } catch (parseError) { + console.error('JSON Parse Error:', parseError); + throw new Error('Invalid JSON response from server'); } - // Transform the emails - const transformedEmails = data.emails.map((email) => ({ - id: String(email.id || ''), + if (data.error) { + throw new Error(data.error); + } + + let emailsArray = []; + if (Array.isArray(data)) { + emailsArray = data; + } else if (data.messages && Array.isArray(data.messages)) { + emailsArray = data.messages; + } else if (data.emails && Array.isArray(data.emails)) { + emailsArray = data.emails; + } else { + console.error('Unexpected data structure:', data); + throw new Error('Invalid response format: emails data not found'); + } + + const validatedEmails = emailsArray.map(email => ({ + id: email.id || Date.now().toString(), + accountId: email.accountId || 1, + from: email.from || '', + fromName: email.fromName || email.from?.split('@')[0] || 'Unknown', + to: email.to || '', subject: email.subject || '(No subject)', - sender: { - name: extractSenderName(email.from || ''), - email: extractEmailAddress(email.from || '') - }, + body: email.body || '', date: email.date || new Date().toISOString(), - isUnread: !email.read + read: !!email.read, + starred: !!email.starred, + category: email.category || 'inbox' })); - console.log('Transformed emails:', transformedEmails); - - setEmails(transformedEmails); + console.log('Processed emails:', validatedEmails); + setEmails(validatedEmails); setMailUrl(data.mailUrl || 'https://espace.slm-lab.net/apps/mail/'); setError(null); } catch (err) { console.error('Fetch error:', err); setError(err instanceof Error ? err.message : 'Error fetching emails'); + setEmails([]); } finally { setLoading(false); setRefreshing(false);