-
Notifications
You must be signed in to change notification settings - Fork 1
/
i18next.ts
30 lines (26 loc) · 852 Bytes
/
i18next.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import type { i18n } from 'i18next';
import type { ParameterizedContext, Next } from 'koa';
import type { Language } from 'types';
interface Options {
lookupSession?: string;
order?: string[];
fallbackLng?: Language;
}
const i18nextMiddleware = (i18next: i18n, options: Options) => {
return async (ctx: ParameterizedContext, next: Next): Promise<void> => {
const { lookupSession = 'lng', order = ['session'], fallbackLng = 'ru' } = options || {};
const lng = order.reduce((acc, value) => {
if(value === 'session') {
const _lng = ctx.session[lookupSession];
if(!_lng) {
return ctx.session[lookupSession] = fallbackLng;
}
return _lng;
}
}, fallbackLng);
await i18next.changeLanguage(lng);
ctx.i18next = i18next;
await next();
};
};
export { i18nextMiddleware };