fastify / fastify/help

How should I localize error.validation with setErrorHandler based on user's request.language

Open
#490 7 comments 0 reactions 0 assignees View on GitHub
Dominant language
No language data
Stars
68
Forks
8
Avg merge
11h 2m
Merged PRs (30d)
2

Description

I want i18n feature for my fastify app, I use `i18next` to localize messages or reply in routes, it's working fine now. Then I want to use `ajv-i18n` for error validation localizing.

But I encountered a problem, I want to localize `error.validation` based on `request.language` injected by `i18next-middleware`, I don't know how to access `request.language` in `setErrorHandler` function, the below is my plugin which is not working now.

The code in `register-after-callback` is not running, but I don't know why. I put the same code in the `register-after-callback` of plugin `fastify-sensible`, the code will run, but still can't access the `request.language`, it's undefined.

I will deeply appreciate any suggestion or help here, if I solved the problem, I will document the i18n solution in this issue for others.

```ts
import localize from 'ajv-i18n';
import fp from 'fastify-plugin';
import i18next from 'i18next';
import i18nextMiddleware from 'i18next-http-middleware';

import resources from '@/locales';

i18next.use(i18nextMiddleware.LanguageDetector).init({
resources,
fallbackLng: 'en',
fallbackNS: 'base',
preload: ['en', 'zh-CN'],
debug: process.env.NODE_ENV !== 'production',
});

/**
* An i18n middleware to be used with Fastify
*
* @see https://github.com/i18next/i18next-http-middleware
*/
export default fp(
async (fastify, options) => {
fastify
.register(i18nextMiddleware.plugin, {
i18next,
ignoreRoutes: [],
})
.after(() => {
fastify.setErrorHandler(function (error, request, reply) {
if (error.validation && error.validation.length > 0) {
const lang = request.language === 'zh-CN' ? 'zh' : request.language;

localize[lang as 'en' | 'zh'](error.validation);
reply.badRequest(error.validation[0].message);
} else {
reply.send(error);
}
});
});
},
{
fastify: '3.x',
name: 'my-plugin-i18n',
},
);
```

Using packages

- [ajv-i18n](https://github.com/ajv-validator/ajv-i18n)
- [i18next](https://github.com/i18next/i18next)
- [i18next-http-middleware](https://github.com/i18next/i18next-http-middleware)

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.