All files / lib/middleware i18n-language-middleware.ts

100% Statements 27/27
100% Branches 10/10
100% Functions 3/3
100% Lines 25/25

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 576x             6x   6x 6x 6x       6x     3x   3x 3x 3x       35x   35x 68x   68x   68x 29x     35x 35x   35x       68x 50x 31x 31x   19x     18x        
import {
  Inject,
  Injectable,
  NestMiddleware,
  forwardRef,
  Type,
} from '@nestjs/common';
import { I18N_OPTIONS, I18N_RESOLVERS } from '../i18n.constants';
import { I18nOptions, I18nResolver, ResolverWithOptions } from '../index';
import { I18nService } from '../services/i18n.service';
import { ModuleRef } from '@nestjs/core';
import { shouldResolve } from '../utils/util';
import { I18nOptionResolver } from '../interfaces/i18n-options.interface';
 
@Injectable()
export class I18nLanguageMiddleware implements NestMiddleware {
  constructor(
    @Inject(I18N_OPTIONS)
    private readonly i18nOptions: I18nOptions,
    @Inject(I18N_RESOLVERS)
    private readonly i18nResolvers: I18nOptionResolver[],
    private readonly i18nService: I18nService,
    private readonly moduleRef: ModuleRef,
  ) {}
 
  async use(req: any, res: any, next: () => void) {
    let language = null;
 
    for (const r of this.i18nResolvers) {
      const resolver = await this.getResolver(r);
 
      language = resolver.resolve(req);
 
      if (language !== undefined) {
        break;
      }
    }
    req.i18nLang = language || this.i18nOptions.fallbackLanguage;
    req.i18nService = this.i18nService;
 
    next();
  }
 
  private async getResolver(r: I18nOptionResolver): Promise<I18nResolver> {
    if (shouldResolve(r)) {
      if (r.hasOwnProperty('use') && r.hasOwnProperty('options')) {
        const resolver = r as ResolverWithOptions;
        return await this.moduleRef.resolve(resolver.use);
      } else {
        return await this.moduleRef.resolve(r as Type<I18nResolver>);
      }
    } else {
      return r as I18nResolver;
    }
  }
}