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

100% Statements 29/29
100% Branches 12/12
100% Functions 3/3
100% Lines 27/27

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 57 58 59 60 615x             5x   5x 5x 5x       5x     3x   3x 3x 3x       40x   40x 40x 96x   96x   96x 12x     96x 34x     40x   40x       96x 48x 36x 36x   12x     48x        
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;
 
    req.i18nService = this.i18nService;
    for (const r of this.i18nResolvers) {
      const resolver = await this.getResolver(r);
 
      language = resolver.resolve(req);
 
      if (language instanceof Promise) {
        language = await (language as Promise<string>);
      }
 
      if (language !== undefined) {
        break;
      }
    }
    req.i18nLang = language || this.i18nOptions.fallbackLanguage;
 
    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;
    }
  }
}