fix: util translation helper

This commit is contained in:
Gabriellvl 2025-02-28 23:59:04 +01:00
parent 80fa6b9f94
commit a8f6f5f776
4 changed files with 27 additions and 23 deletions

View file

@ -12,6 +12,8 @@ import classRouter from './routes/class';
import questionRouter from './routes/question';
import loginRouter from './routes/login';
import homeRouter from './routes/home.js';
const app: Express = express();
const port: string | number = getNumericEnvVar(EnvVars.Port);
@ -33,6 +35,8 @@ app.use('/login', loginRouter);
app.use('/theme', themeRoutes);
app.use('/home', homeRouter);
async function startServer() {
await initORM();

View file

@ -1,39 +1,19 @@
import fs from 'fs';
import path from 'path';
import yaml from 'js-yaml';
import { Request, Response } from 'express';
import { themes } from '../data/themes.js';
import { loadTranslations } from "../util/translationHelper.js";
interface Translations {
curricula_page: {
[key: string]: { title: string; description?: string }; // Optioneel veld description
[key: string]: { title: string; description?: string };
};
}
/**
* Laadt de vertalingen uit een YAML-bestand
*/
function loadTranslations(language: string): Translations {
try {
const filePath = path.join(process.cwd(), '_i18n', `${language}.yml`);
const yamlFile = fs.readFileSync(filePath, 'utf8');
return yaml.load(yamlFile) as Translations;
} catch (error) {
console.error(
`Kan vertaling niet laden voor ${language}, fallback naar Nederlands`
);
console.error(error);
const fallbackPath = path.join(process.cwd(), '_i18n', 'nl.yml');
return yaml.load(fs.readFileSync(fallbackPath, 'utf8')) as Translations;
}
}
/**
* GET /themes Haalt de lijst met thema's op inclusief vertalingen
*/
export function getThemes(req: Request, res: Response) {
const language = (req.query.language as string)?.toLowerCase() || 'nl';
const translations = loadTranslations(language);
const translations = loadTranslations<Translations>(language);
const themeList = themes.map((theme) => {
return {

View file

@ -7,6 +7,8 @@ const router = express.Router();
* @route GET /api/home
* @query {string} language - Taalcode (bijv. 'nl' of 'fr')
* @returns JSON object with homepage data (strengths)
* @example http://localhost:3000/home
* {title, description, strengths: {title, image}}
*/
router.get('/', getHomeScreenData);

View file

@ -0,0 +1,18 @@
import fs from 'fs';
import path from 'path';
import yaml from 'js-yaml';
export function loadTranslations<T>(language: string): T {
try {
const filePath = path.join(process.cwd(), '_i18n', `${language}.yml`);
const yamlFile = fs.readFileSync(filePath, 'utf8');
return yaml.load(yamlFile) as T;
} catch (error) {
console.error(
`Cannot load translation for ${language}, fallen back to dutch`
);
console.error(error);
const fallbackPath = path.join(process.cwd(), '_i18n', 'nl.yml');
return yaml.load(fs.readFileSync(fallbackPath, 'utf8')) as T;
}
}