thortsx
thortsx

Reputation: 2280

Import dynamic folder depending on req.headers['accept-language']

I'm trying to implement a new feature - sending multi-language mail with Nodejs.

I have directory structure like this:

mail-templates
__index.js
__jp
____index.js
____mail1.js
____mail2.js
__en
____index.js
____mail1.js
____mail2.js

In index of en and jp, I will import and export all files in current folder

In index of mail-teamplates, I want to dynamically import folder depending on req.headers['accept-language'] like this:

import * as Mail from `./${variable}` // variable are en or jp depending on accept-language

My question: How I can do that? How I can get accept-language at here to dynamically import folder ?

Upvotes: 0

Views: 180

Answers (2)

Andrei Panturu
Andrei Panturu

Reputation: 109

Is not recommended to do that inside a http callback. The best solution for your problem is to import all of the available languages and just use the preferred language for each request.

Example:

In your mail-templates/index.js:

import * as en from './en';
import * as es from './es';

const defaultLanguage = 'en';
const availableLanguages = { en, es }; 

function getMailByLanguage(language) {
    return availableLanguages[language] || availableLanguages[defaultLanguage];
}

module.exports = getMailByLanguage;

And when you want to use it, just do this:

import * as MailTemplates from './mail-templates';

app.get("/", (req, res) => {
    const language = req.headers["language"];
    const Mail  = MailTemplates.getMailByLanguage(language);

    // Do your stuff's here
    ...
});

Upvotes: 1

Nithin Thampi
Nithin Thampi

Reputation: 3689

You need to to require the module inside the request handler function.

If using express server, you can try something like this.

app.get("/", async(req, res) => {
  const language = req.headers["language"] || "en";
  const module  = `./${language}.js`;
  const greet =  require(module);
  res.json(greet());
  }
)

REPL link. https://repl.it/repls/UsedSelfishVisitor

You can run the below snippet to check the responses based on language header

//Fetching data using laguage: es

fetch("https://UsedSelfishVisitor--five-nine.repl.co", {
  method:"GET",
  headers: {
  language: "es"
}
}).then(res => res.json()).then(data => console.log(data));


//Fetching data using language: en
fetch("https://UsedSelfishVisitor--five-nine.repl.co", {
  method:"GET",
  headers: {
  language: "en"
}
}).then(res => res.json()).then(data => console.log(data));

Upvotes: 1

Related Questions