Files
mwitnessing/pages/api/translations/[...locale].ts
2024-04-28 22:56:41 +03:00

38 lines
1.3 KiB
TypeScript

import fs from 'fs';
import path from 'path';
import { NextApiRequest, NextApiResponse } from 'next';
type Translations = {
[key: string]: string;
};
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
const { locale } = req.query;
const filePath = path.join(process.cwd(), `content/i18n/${locale}.json`);
const translations: Translations = JSON.parse(fs.readFileSync(filePath, 'utf8'));
switch (req.method) {
case 'GET':
try {
res.status(200).json(translations);
} catch (error) {
console.error('Error reading translation file:', error);
res.status(500).json({ error: 'Failed to read translation file' });
}
break;
case 'POST': try {
const newTranslations = req.body;
fs.writeFileSync(filePath, JSON.stringify(newTranslations, null, 2), 'utf8');
res.status(200).json({ status: 'Updated' });
} catch (error) {
console.error('Error writing translation file:', error);
res.status(500).json({ error: 'Failed to update translation file' });
}
break;
default:
res.setHeader('Allow', ['GET', 'POST']);
res.status(405).end(`Method ${req.method} Not Allowed`);
}
}