@softkit/i18n
Version:
This library is a simple wrapper based on [nestjs-i18n](https://nestjs-i18n.com/)
83 lines • 3.38 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.I18nLanguageInterceptor = void 0;
const tslib_1 = require("tslib");
const common_1 = require("@nestjs/common");
const i18n_constants_1 = require("../i18n.constants");
const i18n_service_1 = require("../services/i18n.service");
const core_1 = require("@nestjs/core");
const rxjs_1 = require("rxjs");
const i18n_context_1 = require("../i18n.context");
const utils_1 = require("../utils");
const type_guards_1 = require("../utils/type-guards");
let I18nLanguageInterceptor = class I18nLanguageInterceptor {
constructor(i18nOptions, i18nResolvers, i18nService, moduleRef) {
this.i18nOptions = i18nOptions;
this.i18nResolvers = i18nResolvers;
this.i18nService = i18nService;
this.moduleRef = moduleRef;
}
async intercept(context, next) {
const i18nContext = i18n_context_1.I18nContext.current();
let language = null;
const ctx = (0, utils_1.getContextObject)(context);
// Skip interceptor if language is already resolved (in case of http middleware)
// or when ctx is undefined (unsupported context)
if (ctx === undefined || !!ctx.i18nLang) {
return next.handle();
}
ctx.i18nService = this.i18nService;
for (const r of this.i18nResolvers) {
const resolver = await this.getResolver(r);
language = resolver.resolve(context);
if (language instanceof Promise) {
language = await language;
}
if (language !== undefined) {
break;
}
}
ctx.i18nLang = language || this.i18nOptions.fallbackLanguage;
// Pass down language to handlebars
if (ctx.app && ctx.app.locals) {
ctx.app.locals.i18nLang = ctx.i18nLang;
}
if (!i18nContext) {
ctx.i18nContext = new i18n_context_1.I18nContext(ctx.i18nLang, this.i18nService);
if (!this.i18nOptions.skipAsyncHook) {
return new rxjs_1.Observable((observer) => {
i18n_context_1.I18nContext.createAsync(ctx.i18nContext, async (error) => {
if (error) {
throw error;
}
return next.handle().subscribe(observer);
});
});
}
}
return next.handle();
}
async getResolver(r) {
if ((0, utils_1.shouldResolve)(r)) {
if ((0, type_guards_1.isResolverWithOptions)(r)) {
const resolver = r;
return this.moduleRef.get(resolver.use);
}
else {
return this.moduleRef.get(r);
}
}
else {
return r;
}
}
};
exports.I18nLanguageInterceptor = I18nLanguageInterceptor;
exports.I18nLanguageInterceptor = I18nLanguageInterceptor = tslib_1.__decorate([
(0, common_1.Injectable)(),
tslib_1.__param(0, (0, common_1.Inject)(i18n_constants_1.I18N_OPTIONS)),
tslib_1.__param(1, (0, common_1.Inject)(i18n_constants_1.I18N_RESOLVERS)),
tslib_1.__metadata("design:paramtypes", [Object, Array, i18n_service_1.I18nService,
core_1.ModuleRef])
], I18nLanguageInterceptor);
//# sourceMappingURL=i18n-language.interceptor.js.map