简体   繁体   English

在 Azure 函数中初始化 i18next

[英]Initialize i18next in Azure function

I have an azure http trigger function, which is called by a client with some data and client's culture string eg "en-US".我有一个 azure http 触发器函数,它由客户端调用,其中包含一些数据和客户端的文化字符串,例如“en-US”。 index.js handles the azure request. index.js 处理 azure 请求。 myWorker.js has a function doStuff() which prepares data to return to the client. myWorker.js 有一个函数 doStuff() ,它准备数据返回给客户端。 I am using i18next for localizations.我正在使用 i18next 进行本地化。

index.js needs to pass the culture string to i18next. index.js 需要将文化字符串传递给 i18next。 It seems logical to put i18next in myWorker.js but it needs to load before index.js calls the doStuff function.将 i18next 放在 myWorker.js 中似乎合乎逻辑,但它需要在 index.js 调用 doStuff 函数之前加载。 Forgive me if this is a mess but I'm new to node and don't know the best way to set it up.如果这是一团糟,请原谅我,但我是 node 的新手,不知道设置它的最佳方法。

How does index.js pass the culture string to myworker.js, wait for i18next to load, pass the main data to dostuff() and finish with context.done()? index.js 如何将文化字符串传递给 myworker.js,等待 i18next 加载,将主要数据传递给 dostuff() 并以 context.done() 结束?

index.js
module.exports = async function (context, req) {
    switch (req.body.data.action) {
        case 'doWork':
            let myworker = require('./myWorker')(req.body.data.culture)  //culture string for i18next
            let retval = myworker.dostuff();  //i18next fails as it isn't loaded yet.
            context.res = {
                status: 200, body: {someData: retval}
            };
            break;
        case 'anotherCommand':
        ....
    }
    context.done();
}

myWorker.js
let i18next = require("i18next");
let backend = require("i18next-node-fs-backend");

function dostuff() {
     calc some stuff using i18next.t(key);
}

function setup_i18next(cultr) {
    i18next
        .use(backend)
        .init({
            fallbackLng: 'en',
            lng: cultr,
            backend: {
                loadPath: 'locales/{{lng}}/{{ns}}.json'
            },
            ns: ['myspace1', 'myspace2']
        })
        .then(function (t) {
            ????
         });
}

module.exports = function(cultre) {
    setup_i18next(cultre);
    return {
        dostuff
    }
}

Use fs-backend, like this:使用 fs-backend,像这样:

// i18n.js
const { join } = require('path')
const { readdirSync, lstatSync } = require('fs')
const i18next = require('i18next')
const Backend = require('i18next-fs-backend')
i18next
  .use(Backend)
  .init({
    // debug: true,
    initImmediate: false, // setting initImediate to false, will load the resources synchronously
    fallbackLng: 'en',
    lng: 'en',
    preload: readdirSync(join(__dirname, '../locales')).filter((fileName) => {
      const joinedPath = join(join(__dirname, '../locales'), fileName)
      const isDirectory = lstatSync(joinedPath).isDirectory()
      return isDirectory
    }),
    ns: 'backend-app',
    defaultNS: 'backend-app',
    backend: {
      loadPath: join(__dirname, '../locales/{{lng}}/{{ns}}.json')
    }
  })
module.exports = (lng) => i18next.getFixedT(lng || 'en')

Then just use it like this:然后像这样使用它:

const t = require('../i18n')(lng)
const title = t('invitation.subject')

Based on @adrai's answer (which I never would have figured out) I think it can be tweaked to specify the language in the init.根据@adrai 的回答(我永远不会想到),我认为可以对其进行调整以在 init.d 中指定语言。 Otherwise, we'd unnecessarily load the 'en' translations if another language is specified via lang.否则,如果通过 lang 指定了另一种语言,我们将不必要地加载“en”翻译。

const { join } = require('path')
const { readdirSync, lstatSync } = require('fs')
const i18next = require('i18next')
const SyncBackend = require('i18next-sync-fs-backend')

module.exports = (lang) => {
  i18next
  .use(SyncBackend)
  .init({
    // debug: true,
    initImmediate: false,
    fallbackLng: 'en',
    lng:lang,
    preload: readdirSync(join(__dirname, '../locales')).filter((fileName) => {
      const joinedPath = join(join(__dirname, '../locales'), fileName)
      const isDirectory = lstatSync(joinedPath).isDirectory()
      return isDirectory
    }),
    ns: ['k2locals','sfaDebugger'],
    defaultNS: 'k2locals',
    debug: true,
    backend: {
      loadPath: join(__dirname, '../locales/{{lng}}/{{ns}}.json')
    }
  })
  return i18next.getFixedT(lang || 'en', 'k2locals')
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM