0

我尝试创建一个自定义插件来使用 i18next 插件从后端下载数据,但是,它卡在了数据转储过程中。我正在使用 NextJS 作为前端。

这是 NextJS 的配置文件。

const { i18n } = require('./next-i18next.config.js/index.js')

module.exports = {
  reactStrictMode: true,
  i18n
}

这是 next-18next.config.js 文件内容。

const getDefault = ()=>{
    return {
            parse: data => JSON.parse(data),
            addPath: '/locales/{{lng}}/{{ns}}',
    }
}

class Backend {
  constructor(services, backendOptions, i18nextOptions){
    this.init(services,backendOptions,i18nextOptions)
  }

  init (services,options={},allOptions={}){
      this.services = services;
      this.options = {...getDefault(),...options}; 
      this.allOptions = allOptions;
  }

  async read(language, namespace, callback) {
      const payloadUrl = this.options.payloadUrl; 
      this.data = null; 
      try {
          const response = await fetch(payloadUrl);
          const payloadData = await response.json(); 
          this.data = payloadData; 
      }
      catch(err){
          return callback(err,this.data)
      }

      this.loadUrl(language,namespace,callback); 
  }

    async loadUrl (language,namespace,callback){
      const loadPath = this.options.loadPath;
      const url = this.services.interpolator.interpolate(loadPath, { lng: language, ns: namespace});
      try {
          const response = await fetch(url);
          const data = await response.json();
          return callback(language,namespace,data)
      }

      catch(err){
          console.log("Error while fetching payload ", err)
          callback(err,null)
      }
    }

     save (language, namespace, data) {
      console.log(language,namespace,data); 
     }

     create (language, namespace, key, fallbackValue) {
        console.log(language,namespace,key,fallbackValue)
     }

    dumpData(language,namespace,data){
      const filePath = this.services.interpolator.interpolate(this.options.addPath, { lng: language, ns: namespace});
      // need to find a way to dump the file into the given filePath, (right now 
      // I cannot find proper way to use fs library)
      console.log(filePath, "is the file path")
      console.log("data we dumping ", data); 
    }
}

Backend.type = "backend";
module.exports =  Backend;

我正在关注https://github.com/i18next/i18next-http-backend并且不知道他们如何将我们从后端获得的有效负载转储到特定文件夹。我尝试手动添加fs库,但是我们正在使用 NextJS 并且使用fs给了我错误Can't resolve 'fs'。我们如何将从后端收到的数据转储到所需的位置?

4

1 回答 1

0

回调签名错误,回调(语言,命名空间,数据)不正确。签名应该是 callback(error, result) => 这意味着您可以将其更改为:callback(null, data)

此外,所有这些都不是异步函数,普通的基于回调的函数,如下所述:https ://www.i18next.com/misc/creating-own-plugins#backend

顺便说一句:如果您从后端获取数据,为什么不简单地使用i18next-http-backend并调整 loadPath 和/或 parse 选项和/或 request 选项:https ://github.com/i18next/i18next -http-backend#backend-options

于 2022-02-15T15:52:43.660 回答