Lau*_*ris 7 javascript backend node.js adonis.js lucid
我正在对我的 API 应用国际化,但我遇到了一些与 Antl 和验证消息相关的问题。
对于标准响应消息,我将根据用户设置的区域设置返回。我创建了一个切换语言环境的路由,并设置为一个 cookie 和一个全局中间件,以从 cookie 中获取语言环境,然后我只返回存储在语言环境资源中的消息。
全局中间件:
class Locale {
async handle ({ request, antl }, next) {
const lang = request.cookie('lang')
if (lang) {
antl.switchLocale(lang)
}
await next()
}
}
Run Code Online (Sandbox Code Playgroud)
路线:
Route.get('/switch/:lang', ({ params, antl, request, response }) => {
// Getting the current available locales
const locales = antl.availableLocales()
try {
// Saving into cookies
if (locales.indexOf(params.lang) > -1) {
response.cookie('lang', params.lang, { path: '/' })
}
return response.status(200).send({ message: 'Locale changed succesfully' })
} catch (err) {
return response.status(err.status).send({ error: 'Something went wrong while trying to switch locales', data: { message: err.message || 'Error message not found', name: err.name } })
}
})
Run Code Online (Sandbox Code Playgroud)
但我有两个带有验证消息的文件:
PT - https://github.com/LauraBeatris/xpack-adonis-api/blob/develop/resources/locales/pt/validation.json
EN - https://github.com/ LauraBeatris/xpack-adonis-api/blob/develop/resources/locales/en/validation.json
我想根据用户设置的当前语言环境返回验证消息,但问题是验证器类的 get 方法无法像其他中间件一样访问 antl 上下文对象。
验证器的消息方法:
get messages () {
return Antl.list('validation')
}
Run Code Online (Sandbox Code Playgroud)
但是,当我使用中间件上下文提供的 antl 对象更改区域设置时,它不会在全局提供程序中更改,因此验证消息将始终返回默认区域设置,而不是用户在中间件中设置的区域设置. 例如,我想将语言环境切换路由与该 antl 全局提供程序集成,以便我能够返回葡萄牙语验证消息。
这是我的项目的仓库:https : //github.com/LauraBeatris/xpack-adonis-api
要在验证器的方法Antl中使用该对象get messages(),您需要使用this.ctx.antl. 喜欢 :
var antl = this.ctx.antl;
...
antl.formatMessage(...)
Run Code Online (Sandbox Code Playgroud)
Adonis 不存储Antl查询之间使用的语言。所有路由都必须具有应用该语言(您创建的语言)的中间件。例子 :
var antl = this.ctx.antl;
...
antl.formatMessage(...)
Run Code Online (Sandbox Code Playgroud)
如果你想让所有路由都有这个中间件,你必须将它添加到start/kernel.js. : https: //adonisjs.com/docs/4.1/middleware#_global_middleware
如果您需要更多信息,请不要犹豫:)
| 归档时间: |
|
| 查看次数: |
1315 次 |
| 最近记录: |