Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 9 additions & 8 deletions src/app.module.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Module } from '@nestjs/common';
import { APP_GUARD, APP_INTERCEPTOR } from '@nestjs/core';
import { APP_GUARD } from '@nestjs/core';
import { ConfigModule } from '@nestjs/config';
import { TypeOrmModule } from '@nestjs/typeorm';
import { ScheduleModule } from '@nestjs/schedule';
Expand All @@ -9,6 +9,7 @@ import { SearchModule } from './search/search.module';
import { AnalyticsModule } from './analytics/analytics.module';
import { ShardingModule } from './sharding/sharding.module';

import { EmailModule } from './email-marketing/email.module';
import { IndexOptimizationModule } from './database/index-optimization/index-optimization.module';
import { RateLimitingModule } from './rate-limiting/rate-limiting.module';
import { QuotaGuard } from './rate-limiting/guards/quota.guard';
Expand All @@ -20,6 +21,7 @@ import { DataPipelineModule } from './data-pipeline/data-pipeline.module';
import { CanaryModule } from './canary/canary.module';
import { IncidentManagementModule } from './incident-management/incident-management.module';
import { MonitoringModule } from './monitoring/monitoring.module';
import { I18nModule as AppI18nModule } from './i18n/i18n.module';
import { RequestTimeoutInterceptor } from './common/interceptors/request-timeout.interceptor';
import { IdempotencyModule } from './common/modules/idempotency.module';
import { IdempotencyInterceptor } from './common/interceptors/idempotency.interceptor';
Expand Down Expand Up @@ -80,6 +82,8 @@ const featureFlags = loadFeatureFlags();

// ✅ feature-flagged caching
...(featureFlags.ENABLE_CACHING ? [CachingModule] : []),
// i18n support
AppI18nModule,

// ✅ courses module with enrollment and prerequisite enforcement
CoursesModule,
Expand All @@ -98,11 +102,8 @@ const featureFlags = loadFeatureFlags();
GamificationModule,
],
controllers: [AppController],
providers: [
SlackService,
...(featureFlags.ENABLE_RATE_LIMITING ? [{ provide: APP_GUARD, useClass: QuotaGuard }] : []),
{ provide: APP_INTERCEPTOR, useClass: RequestTimeoutInterceptor },
{ provide: APP_INTERCEPTOR, useClass: IdempotencyInterceptor },
],
providers: featureFlags.ENABLE_RATE_LIMITING
? [{ provide: APP_GUARD, useClass: QuotaGuard }]
: [],
})
export class AppModule {}
export class AppModule {}
21 changes: 21 additions & 0 deletions src/i18n/i18n.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { Controller, Get, Query } from '@nestjs/common';
import { I18nWrapperService } from './i18n.service';

@Controller('i18n')
export class I18nController {
constructor(private readonly i18n: I18nWrapperService) {}

@Get('locales')
getLocales() {
return this.i18n.getSupportedLocales();
}

@Get('translate')
translate(@Query('key') key: string, @Query('lang') lang?: string) {
if (!key) return { error: 'missing_key' };
const locale = lang || 'en';
const value = this.i18n.translate(key, locale);
const direction = this.i18n.getDirection(locale);
return { key, locale, value, direction };
}
}
18 changes: 18 additions & 0 deletions src/i18n/i18n.middleware.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { Injectable, NestMiddleware } from '@nestjs/common';
import { Request, Response, NextFunction } from 'express';
import { I18nWrapperService } from './i18n.service';
import { RequestWithLocale } from '../common/types/request-with-locale';

@Injectable()
export class LocaleMiddleware implements NestMiddleware {
constructor(private readonly wrapper: I18nWrapperService) {}

use(req: RequestWithLocale, res: Response, next: NextFunction) {
const lang = (req.query.lang as string) || (req.headers['x-lang'] as string) || (req.headers['lang'] as string) || 'en';
const short = String(lang).split(',')[0].split('-')[0];
const direction = this.wrapper.getDirection(short);
res.setHeader('Content-Direction', direction);
req.resolvedLocale = short;
next();
}
}
16 changes: 16 additions & 0 deletions src/i18n/i18n.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { Module, MiddlewareConsumer, NestModule } from '@nestjs/common';
import { I18nController } from './i18n.controller';
import { I18nWrapperService } from './i18n.service';
import { LocaleMiddleware } from './i18n.middleware';

@Module({
imports: [],
controllers: [I18nController],
providers: [I18nWrapperService, LocaleMiddleware],
exports: [I18nWrapperService],
})
export class I18nModule implements NestModule {
configure(consumer: MiddlewareConsumer) {
consumer.apply(LocaleMiddleware).forRoutes('*');
}
}
88 changes: 88 additions & 0 deletions src/i18n/i18n.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
import { Injectable, Logger } from '@nestjs/common';
import { readdirSync, readFileSync } from 'fs';
import { extname, join } from 'path';

const RTL_LANGS = ['ar', 'he', 'fa', 'ur'];
const DEFAULT_LOCALE = 'en';

interface LocaleDefinition {
code: string;
name: string;
direction: 'ltr' | 'rtl';
}

@Injectable()
export class I18nWrapperService {
private readonly logger = new Logger(I18nWrapperService.name);
private readonly localesPath = join(__dirname, 'locales');
private readonly fallbackLocale = DEFAULT_LOCALE;
private readonly supported: LocaleDefinition[] = [
{ code: 'en', name: 'English', direction: 'ltr' },
{ code: 'ar', name: 'Arabic', direction: 'rtl' },
];
private readonly bundles: Record<string, Record<string, unknown>> = {};

constructor() {
this.loadBundles();
}

getSupportedLocales() {
return this.supported;
}

getDirection(locale: string) {
return this.isRtl(locale) ? 'rtl' : 'ltr';
}

translate(key: string, locale: string) {
const normalized = this.normalizeLocale(locale);
const bundle = this.bundles[normalized] || this.bundles[this.fallbackLocale] || {};
return this.lookup(bundle, key) ?? key;
}

isRtl(locale: string) {
if (!locale) return false;
return RTL_LANGS.includes(this.normalizeLocale(locale));
}

private loadBundles() {
try {
const localeDirs = readdirSync(this.localesPath, { withFileTypes: true }).filter((entry) => entry.isDirectory());
for (const localeDir of localeDirs) {
const locale = localeDir.name;
const bundle: Record<string, unknown> = {};
const localeFolder = join(this.localesPath, locale);
const files = readdirSync(localeFolder, { withFileTypes: true }).filter((entry) => entry.isFile());

for (const file of files) {
if (extname(file.name).toLowerCase() !== '.json') continue;
const namespace = file.name.replace(/\.json$/i, '');
const raw = readFileSync(join(localeFolder, file.name), 'utf8');
bundle[namespace] = JSON.parse(raw);
}

this.bundles[locale] = bundle;
}
} catch (error) {
this.logger.error('Failed to load locale bundles', error as Error);
}
}

private normalizeLocale(locale: string) {
return String(locale).split(',')[0].split('-')[0].toLowerCase();
}

private lookup(bundle: Record<string, unknown>, key: string): string | undefined {
const segments = key.split('.');
let result: unknown = bundle;

for (const segment of segments) {
if (typeof result !== 'object' || result === null) {
return undefined;
}
result = (result as Record<string, unknown>)[segment];
}

return typeof result === 'string' ? result : undefined;
}
}
5 changes: 5 additions & 0 deletions src/i18n/locales/ar/common.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"greeting": "مرحبا",
"farewell": "مع السلامة",
"welcome_message": "مرحبًا بكم في TeachLink"
}
5 changes: 5 additions & 0 deletions src/i18n/locales/en/common.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"greeting": "Hello",
"farewell": "Goodbye",
"welcome_message": "Welcome to TeachLink"
}
Loading