Files
mwitnessing/pages/api/translations/[...locale].ts
2024-04-29 01:28:59 +03:00

85 lines
3.0 KiB
TypeScript

import { NextApiRequest, NextApiResponse } from 'next';
import fs from 'fs';
import path from 'path';
import common from "../../../src/helpers/common";
function flattenTranslations(data) {
const result = {};
function recurse(cur, prop) {
if (Object(cur) !== cur) {
result[prop] = cur;
} else if (Array.isArray(cur)) {
for (let i = 0, l = cur.length; i < l; i++)
recurse(cur[i], prop ? prop + "." + i : "" + i);
if (l == 0)
result[prop] = [];
} else {
let isEmpty = true;
for (let p in cur) {
isEmpty = false;
recurse(cur[p], prop ? prop + "." + p : p);
}
if (isEmpty)
result[prop] = {};
}
}
recurse(data, "");
return result;
}
function unflattenTranslations(data) {
const result = {};
for (let i in data) {
const keys = i.split('.');
keys.reduce((r, e, j) => {
return r[e] || (r[e] = isNaN(Number(keys[j + 1])) ? (keys.length - 1 === j ? data[i] : {}) : []);
}, result);
}
return result;
}
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
const { locale } = req.query;
const filePath = path.join(process.cwd(), `content/i18n/${locale.join(".")}.json`);
const modifiedFilePath = path.join(process.cwd(), `content/i18n/${locale}.modified.json`);
switch (req.method) {
case 'GET':
let flat = common.parseBool(req.query.flat);
try {
const fileContents = fs.readFileSync(filePath, 'utf8');
let translations = JSON.parse(fileContents);
if (fs.existsSync(modifiedFilePath)) {
const modifiedTranslations = JSON.parse(fs.readFileSync(modifiedFilePath, 'utf8'));
translations = { ...translations, ...modifiedTranslations };
}
if (flat) {
translations = flattenTranslations(translations);
}
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;
const reconstructedTranslations = unflattenTranslations(newTranslations);
fs.writeFileSync(filePath, JSON.stringify(reconstructedTranslations, 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`);
}
}