-
Notifications
You must be signed in to change notification settings - Fork 103
/
i18n.context.ts
75 lines (64 loc) · 1.85 KB
/
i18n.context.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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import { ArgumentsHost } from '@nestjs/common';
import { AsyncLocalStorage } from 'async_hooks';
import { I18nTranslator, I18nValidationError } from './interfaces';
import { I18nService, TranslateOptions } from './services/i18n.service';
import { Path, PathValue } from './types';
import { getContextObject } from './utils';
export class I18nContext<K = Record<string, unknown>>
implements I18nTranslator<K>
{
private static storage = new AsyncLocalStorage<I18nContext>();
private static counter = 1;
readonly id = I18nContext.counter++;
get i18n(): I18nContext<K> | undefined {
return this;
}
constructor(
readonly lang: string,
readonly service: I18nService<K>,
) {}
public translate<P extends Path<K> = any, R = PathValue<K, P>>(
key: P,
options?: TranslateOptions,
) {
options = {
lang: this.lang,
...options,
};
return this.service.translate<P, R>(key, options);
}
public t<P extends Path<K> = any, R = PathValue<K, P>>(
key: P,
options?: TranslateOptions,
) {
return this.translate<P, R>(key, options);
}
public validate(
value: any,
options?: TranslateOptions,
): Promise<I18nValidationError[]> {
options = {
lang: this.lang,
...options,
};
return this.service.validate(value, options);
}
static create(ctx: I18nContext, next: (...args: any[]) => void): void {
this.storage.run(ctx, next);
}
static async createAsync<T>(
ctx: I18nContext,
next: (...args: any[]) => Promise<T>,
): Promise<T> {
return this.storage.run(ctx, next);
}
static current<K = Record<string, unknown>>(
context?: ArgumentsHost,
): I18nContext<K> | undefined {
const i18n = this.storage.getStore() as I18nContext<K> | undefined;
if (!i18n && !!context) {
return getContextObject(context)?.i18nContext;
}
return i18n;
}
}