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

74 lines
1.9 KiB
TypeScript
Raw Normal View History

2023-03-12 23:19:53 -04:00
import { Application, Router } from "https://deno.land/x/oak@v12.1.0/mod.ts";
2023-03-08 09:53:11 -05:00
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;
2023-03-13 00:00:01 -04:00
for (const lng of ["en", 'ja', "zh-CN"]) {
2023-03-12 23:19:53 -04:00
const translationPath = path.join(
__dirname,
`../src/i18n/translation/${lng}.json`,
);
2023-03-08 09:53:11 -05:00
let translations: Record<string, string> = {};
try {
translations = JSON.parse(await Deno.readTextFile(translationPath));
} catch (error) {}
2023-03-12 23:19:53 -04: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
2023-03-12 23:19:53 -04:00
.map((i) => [i, i] as const),
]
.sort(([a], [b]) => a.localeCompare(b)),
2023-03-08 09:53:11 -05:00
);
2023-03-12 23:19:53 -04: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();
}
2023-03-12 23:19:53 -04:00
let delayId: number | null = null;
2023-03-08 10:25:48 -05:00
2023-03-12 23:19:53 -04:00
router.post("/locales/add/:lng/:ns", async (context) => {
2023-03-08 10:25:48 -05:00
try {
// ns, lng is ignored
2023-03-12 23:19:53 -04:00
const body: Record<string, string> = await context.request.body({
type: "json",
}).value;
2023-03-08 10:25:48 -05:00
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-12 23:19:53 -04: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());
2023-03-12 23:19:53 -04:00
console.log(`Listening on port ${PORT}...`);
2023-03-08 09:53:11 -05:00
await app.listen({ port: PORT });