pixelbrew-webseite/pages/api/update-blog.js
2025-09-11 00:00:17 +02:00

64 lines
1.8 KiB
JavaScript

import { supabaseAdmin } from '../../lib/supabase';
export default async function handler(req, res) {
if (req.method !== 'POST') {
console.log('Method not allowed:', req.method);
return res.status(405).json({ error: 'Method not allowed' });
}
try {
// Get user from supabase session
const { data: sessionData, error: authError } = await supabaseAdmin.auth.getUser(req.cookies['sb-access-token']);
if (authError || !sessionData?.user) {
return res.status(401).json({ error: 'Unauthorized' });
}
const user = sessionData.user;
const data = req.body;
if (!Array.isArray(data)) {
console.log('Invalid data format - not an array');
return res.status(400).json({ error: 'Data must be an array' });
}
const results = [];
for (const entry of data) {
const content = Array.isArray(entry.content) ? entry.content : [];
const cleanEntry = {
title: entry.title || '',
date: entry.date || '',
description: entry.description || '',
slug: entry.slug || '',
image: entry.image || '',
content: content,
author_id: user.id,
updated_at: new Date().toISOString()
}; const { data: result, error } = await supabaseAdmin
.from('blog_entries')
.upsert(cleanEntry, {
onConflict: 'slug',
returning: 'minimal'
});
if (error) {
console.error('Supabase upsert error:', error);
throw error;
}
results.push(result);
}
res.status(200).json({
message: 'Blog entries updated successfully',
results
});
} catch (error) {
console.error('Error updating blog entries:', error);
res.status(500).json({ error: 'Internal server error' });
}
}