perplexity-hackathon-LawMitra / perplexity_hackathon / src / middleware / translationMiddleware.ts
translationMiddleware.ts
Raw
import { Request, Response, NextFunction } from 'express';
import { translationService } from '../services/translationService';

interface TranslatedRequest extends Request {
  originalText?: string;
  translatedText?: string;
  detectedLanguage?: string;
  targetLanguage?: string;
}

export const translateIncomingText = async (
  req: TranslatedRequest,
  res: Response,
  next: NextFunction
) => {
  try {
    // Skip translation if no text in body
    if (!req.body.text) {
      return next();
    }

    // Store original text
    req.originalText = req.body.text;

    // Detect language if not specified
    if (!req.body.language) {
      const detection = await translationService.detectLanguage(req.body.text);
      req.detectedLanguage = detection.language;
    }

    // Translate to English if not already in English
    const sourceLanguage = req.body.language || req.detectedLanguage;
    if (sourceLanguage && sourceLanguage !== 'en') {
      const translation = await translationService.translateToEnglish(req.body.text);
      req.translatedText = translation.translatedText;
      // Replace the text in the request with translated version
      req.body.text = translation.translatedText;
    }

    next();
  } catch (error) {
    console.error('Translation middleware error:', error);
    next(error);
  }
};

export const translateOutgoingResponse = async (
  req: TranslatedRequest,
  res: Response,
  next: NextFunction
) => {
  try {
    // Store the original json method
    const originalJson = res.json;

    // Override the json method
    res.json = function(body: any) {
      const translatedBody = Promise.resolve().then(async () => {
        try {
          // If there's a response text and original request wasn't in English
          if (body.text && req.detectedLanguage && req.detectedLanguage !== 'en') {
            const translation = await translationService.translateFromEnglish(
              body.text,
              req.detectedLanguage
            );
            body.originalText = body.text;
            body.text = translation.translatedText;
            body.language = req.detectedLanguage;
          }
          return body;
        } catch (error) {
          console.error('Response translation error:', error);
          return body;
        }
      });

      return originalJson.call(res, body);
    };

    next();
  } catch (error) {
    console.error('Translation middleware error:', error);
    next(error);
  }
};