Commit f0f42bd7 authored by nanahira's avatar nanahira

i18n support next with args

parent 765dfff5
import { MiddlewareDispatcher } from '../middleware-dispatcher/middleware-dispatcher';
import { parseI18n } from '../utility/parse-i18n';
import { I18nMiddleware, I18nOptions } from './types';
import {
I18nMiddleware,
I18nMiddlewareFunc,
I18nMiddlewareNext,
I18nOptions,
} from './types';
import { patchStringInObject } from '../patch-string-in-object';
import { DynamicMiddlewareDispatcher } from '../middleware-dispatcher';
class I18nMiddlewareDispatcher<
Ex extends any[],
> extends DynamicMiddlewareDispatcher<I18nMiddlewareFunc<Ex>> {
constructor() {
super({
acceptResult: (res) => res != null,
errorHandler: (e) => {
throw e;
},
});
}
middlewares: I18nMiddleware<Ex>[] = [];
async buildMiddlewares() {
return this.middlewares.map(
(mw) =>
(locale: string, text: string, ...args: any[]) => {
const ex = args.slice(0, -1) as Ex;
const next = args[args.length - 1] as I18nMiddlewareNext<Ex>;
return mw(locale, text, next, ...ex);
},
);
}
}
export class I18n<Ex extends any[] = []> {
constructor(private options: I18nOptions) {}
......@@ -9,35 +40,20 @@ export class I18n<Ex extends any[] = []> {
locales = new Set(this.options.locales);
defaultLocale = this.options.defaultLocale ?? this.options.locales[0];
private mw = new MiddlewareDispatcher<
(locale: string, text: string, ...ex: Ex) => string | undefined
>({
acceptResult: (res) => res != null,
errorHandler: (e) => {
throw e;
},
});
private shadowMiddlewares: I18nMiddleware<Ex>[] = [];
private mw = new I18nMiddlewareDispatcher();
middleware(mw: I18nMiddleware<Ex>, prior = false) {
this.mw.middleware((locale, text, ...args) => {
const ex = args.slice(0, -1) as Ex;
const next = args[args.length - 1] as () => Promise<string | undefined>;
return mw(locale, text, next, ...ex);
}, prior);
if (prior) {
this.shadowMiddlewares.unshift(mw);
this.mw.middlewares.unshift(mw);
} else {
this.shadowMiddlewares.push(mw);
this.mw.middlewares.push(mw);
}
return this;
}
removeMiddleware(mw: I18nMiddleware<Ex>) {
const idx = this.shadowMiddlewares.indexOf(mw);
const idx = this.mw.middlewares.indexOf(mw);
if (idx >= 0) {
this.shadowMiddlewares.splice(idx, 1);
this.mw.middlewares.splice(idx, 1);
}
return this;
......
import { MiddlewareNext } from '../middleware-dispatcher';
import { Awaitable } from '../types';
export type I18nMiddlewareFunc<Ex extends any[] = []> = (
locale: string,
text: string,
...ex: Ex
) => string | undefined;
export type I18nMiddlewareNext<Ex extends any[] = []> = MiddlewareNext<
I18nMiddlewareFunc<Ex>
>;
export type I18nMiddleware<Ex extends any[] = []> = (
locale: string,
text: string,
next: () => Promise<string | undefined>,
next: I18nMiddlewareNext<Ex>,
...ex: Ex
) => Awaitable<string | undefined>;
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment