import fs from 'fs'; import path from 'path'; interface Halaman { id: number; name: string; url: string; level: number; parent?: number; icon?: string; role: string[]; } const filePath = path.resolve('data/mock/halaman.json'); // Helper to read JSON file const readData = (): Halaman[] => { try { const data = fs.readFileSync(filePath, 'utf-8'); return JSON.parse(data); } catch (error) { console.error('Error reading halaman.json:', error); return []; } }; // Helper to write JSON file const writeData = (data: Halaman[]): boolean => { try { fs.writeFileSync(filePath, JSON.stringify(data, null, 4), 'utf-8'); return true; } catch (error) { console.error('Error writing halaman.json:', error); return false; } }; export default defineEventHandler(async (event) => { const method = event.method; const id = event.context.params?.id; if (!id) { return { success: false, message: 'Invalid ID' }; } const numericId = Number(id); // GET - Get single halaman by ID if (method === 'GET') { try { const data = readData(); const halaman = data.find(item => item.id === numericId); if (halaman) { return { success: true, data: halaman }; } else { return { success: false, message: 'Halaman tidak ditemukan' }; } } catch (error) { return { success: false, message: 'Gagal memuat data halaman', error: error instanceof Error ? error.message : 'Unknown error' }; } } // PUT - Update halaman role if (method === 'PUT') { try { const body = await readBody(event); const data = readData(); const index = data.findIndex(item => item.id === numericId); if (index === -1) { return { success: false, message: 'Halaman tidak ditemukan' }; } // Update only the role field data[index] = { ...data[index], role: body.role || [] }; const success = writeData(data); if (success) { return { success: true, message: 'Role halaman berhasil diupdate', data: data[index] }; } else { throw new Error('Failed to save data'); } } catch (error) { return { success: false, message: 'Gagal mengupdate role halaman', error: error instanceof Error ? error.message : 'Unknown error' }; } } return { success: false, message: 'Method not allowed' }; });