s3si.ts/gui/scripts/i18n-backend.ts

66 lines
1.8 KiB
TypeScript
Raw Normal View History

2023-03-08 09:53:11 -05:00
import { Application, Router } from 'https://deno.land/x/oak@v12.1.0/mod.ts';
import * as path from "https://deno.land/std@0.178.0/path/mod.ts";
const PORT = 1421;
const __dirname = path.dirname(path.fromFileUrl(import.meta.url));
const app = new Application();
const router = new Router();
2023-03-08 10:25:48 -05:00
const keys: Set<string> = new Set();
2023-03-08 09:53:11 -05:00
2023-03-08 10:25:48 -05:00
async function updateFile() {
delayId = null;
for (const lng of ['en', 'zh-CN']) {
2023-03-08 09:53:11 -05:00
const translationPath = path.join(__dirname, `../src/i18n/translation/${lng}.json`);
let translations: Record<string, string> = {};
try {
translations = JSON.parse(await Deno.readTextFile(translationPath));
} catch (error) {}
2023-03-08 10:25:48 -05:00
const toAdd = [...keys].filter(k => !Object.keys(translations).includes(k));
2023-03-08 09:53:11 -05:00
translations = Object.fromEntries(
2023-03-08 10:25:48 -05:00
[
...Object.entries(translations),
...toAdd
.map(i => [i, i] as const)]
.sort(([a], [b]) => a.localeCompare(b)),
2023-03-08 09:53:11 -05:00
);
2023-03-08 10:25:48 -05:00
console.log('Add keys:', toAdd, 'for', lng);
2023-03-08 09:53:11 -05:00
await Deno.writeTextFile(
translationPath,
JSON.stringify(translations, null, 2),
);
2023-03-08 10:25:48 -05:00
}
keys.clear();
}
let delayId: number|null = null;
router.post('/locales/add/:lng/:ns', async (context) => {
try {
// ns, lng is ignored
const body: Record<string,string> = await context.request.body({ type: 'json' }).value;
for (const key of Object.keys(body)) {
keys.add(key);
}
2023-03-08 09:53:11 -05:00
2023-03-08 10:25:48 -05:00
if (delayId !== null) {
clearTimeout(delayId);
}
delayId = setTimeout(updateFile, 1000);
2023-03-08 09:53:11 -05:00
context.response.status = 200;
2023-03-08 10:25:48 -05:00
context.response.body = { message: 'Translation added.' };
2023-03-08 09:53:11 -05:00
} catch (error) {
context.response.status = 500;
context.response.body = { message: error.message };
}
});
app.use(router.routes());
app.use(router.allowedMethods());
console.log(`Listening on port ${PORT}...`)
await app.listen({ port: PORT });