All files / lib i18n.module.ts

86.67% Statements 65/75
84% Branches 21/25
94.74% Functions 18/19
86.3% Lines 63/73

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 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 2426x                 6x             6x 6x                 6x 6x 6x 6x 6x 6x   6x   6x               6x   10x 10x         3x       3x 1x     1x     16x       2x         8x 8x         8x     8x 8x               8x     8x 8x               8x         8x                                 2x 2x 2x 2x       2x                                       2x 2x                             2x     2x 2x 2x                     2x     2x 2x 2x                     12x   12x 12x 1x     12x       10x     4x 2x 2x 2x         2x   2x     2x 2x         2x   2x       4x        
import {
  DynamicModule,
  Global,
  Logger,
  MiddlewareConsumer,
  Module,
  NestModule,
  Provider,
} from '@nestjs/common';
import {
  I18N_OPTIONS,
  I18N_TRANSLATIONS,
  I18N_LANGUAGES,
  I18nTranslation,
  I18N_RESOLVERS,
} from './i18n.constants';
import { I18nService } from './services/i18n.service';
import { I18nRequestScopeService } from './services/i18n-request-scope.service';
import {
  I18nAsyncOptions,
  I18nOptions,
  I18nOptionsFactory,
  ResolverWithOptions,
  I18nOptionResolver,
} from './interfaces/i18n-options.interface';
import { ValueProvider } from '@nestjs/common/interfaces';
import { parseTranslations, getLanguages } from './utils/parse';
import * as path from 'path';
import { I18nLanguageMiddleware } from './middleware/i18n-language-middleware';
import { HttpAdapterHost, ModuleRef } from '@nestjs/core';
import { getI18nResolverOptionsToken } from './decorators/i18n-resolver-options.decorator';
import { shouldResolve } from './utils/util';
 
const logger = new Logger('I18nService');
 
const defaultOptions: Partial<I18nOptions> = {
  filePattern: '*.json',
  resolvers: [],
  saveMissing: true,
};
 
@Global()
@Module({})
export class I18nModule implements NestModule {
  constructor(
    private readonly httpAdapterHost: HttpAdapterHost,
    private readonly moduleRef: ModuleRef,
  ) {}
 
  configure(consumer: MiddlewareConsumer): MiddlewareConsumer | void {
    const adapterName =
      this.httpAdapterHost.httpAdapter &&
      this.httpAdapterHost.httpAdapter.constructor &&
      this.httpAdapterHost.httpAdapter.constructor.name;
 
    if (adapterName === 'FastifyAdapter') {
      this.moduleRef
        .create(I18nLanguageMiddleware)
        .then(i18nLanguageMiddleware => {
          this.httpAdapterHost.httpAdapter
            .getInstance()
            .addHook('preHandler', (req, res, done) => {
              i18nLanguageMiddleware.use(req, res, done);
            });
        });
    } else {
      consumer.apply(I18nLanguageMiddleware).forRoutes('*');
    }
  }
 
  static forRoot(options: I18nOptions): DynamicModule {
    options = this.sanitizeI18nOptions(options);
    const i18nOptions: ValueProvider = {
      provide: I18N_OPTIONS,
      useValue: options,
    };
 
    const translationsProvider = {
      provide: I18N_TRANSLATIONS,
      useFactory: async (): Promise<I18nTranslation> => {
        try {
          return await parseTranslations(options);
        } catch (e) {
          logger.error('parsing translation error', e);
          return {};
        }
      },
    };
 
    const languagessProvider = {
      provide: I18N_LANGUAGES,
      useFactory: async (): Promise<string[]> => {
        try {
          return await getLanguages(options);
        } catch (e) {
          logger.error('failed getting languages', e);
          return [];
        }
      },
    };
 
    const resolversProvider = {
      provide: I18N_RESOLVERS,
      useValue: options.resolvers || [],
    };
 
    return {
      module: I18nModule,
      providers: [
        { provide: Logger, useValue: logger },
        I18nService,
        I18nRequestScopeService,
        i18nOptions,
        translationsProvider,
        languagessProvider,
        resolversProvider,
        ...this.createResolverProviders(options.resolvers),
      ],
      exports: [I18nService, I18nRequestScopeService, languagessProvider],
    };
  }
 
  static forRootAsync(options: I18nAsyncOptions): DynamicModule {
    const asyncOptionsProvider = this.createAsyncOptionsProvider(options);
    const asyncTranslationProvider = this.createAsyncTranslationProvider();
    const asyncLanguagesProvider = this.createAsyncLanguagesProvider();
    const resolversProvider = {
      provide: I18N_RESOLVERS,
      useValue: options.resolvers || [],
    };
    return {
      module: I18nModule,
      imports: options.imports || [],
      providers: [
        { provide: Logger, useValue: logger },
        asyncOptionsProvider,
        asyncTranslationProvider,
        asyncLanguagesProvider,
        I18nService,
        I18nRequestScopeService,
        resolversProvider,
        ...this.createResolverProviders(options.resolvers),
      ],
      exports: [I18nService, I18nRequestScopeService, asyncLanguagesProvider],
    };
  }
 
  private static createAsyncOptionsProvider(
    options: I18nAsyncOptions,
  ): Provider {
    Eif (options.useFactory) {
      return {
        provide: I18N_OPTIONS,
        useFactory: options.useFactory,
        inject: options.inject || [],
      };
    }
    return {
      provide: I18N_OPTIONS,
      useFactory: async (optionsFactory: I18nOptionsFactory) =>
        await optionsFactory.createI18nOptions(),
      inject: [options.useClass || options.useExisting],
    };
  }
 
  private static createAsyncTranslationProvider(): Provider {
    return {
      provide: I18N_TRANSLATIONS,
      useFactory: async (options: I18nOptions): Promise<I18nTranslation> => {
        options = this.sanitizeI18nOptions(options);
        try {
          return await parseTranslations(options);
        } catch (e) {
          logger.error('parsing translation error', e);
          return {};
        }
      },
      inject: [I18N_OPTIONS],
    };
  }
 
  private static createAsyncLanguagesProvider(): Provider {
    return {
      provide: I18N_LANGUAGES,
      useFactory: async (options: I18nOptions): Promise<string[]> => {
        options = this.sanitizeI18nOptions(options);
        try {
          return await getLanguages(options);
        } catch (e) {
          logger.error('parsing translation error', e);
          return [];
        }
      },
      inject: [I18N_OPTIONS],
    };
  }
 
  private static sanitizeI18nOptions(options: I18nOptions) {
    options = { ...defaultOptions, ...options };
 
    options.path = path.normalize(options.path + path.sep);
    if (!options.filePattern.startsWith('*.')) {
      options.filePattern = '*.' + options.filePattern;
    }
 
    return options;
  }
 
  private static createResolverProviders(resolvers?: I18nOptionResolver[]) {
    return (resolvers || [])
      .filter(shouldResolve)
      .reduce<Provider[]>((providers, r) => {
        if (r.hasOwnProperty('use') && r.hasOwnProperty('options')) {
          const resolver = r as ResolverWithOptions;
          const optionsToken = getI18nResolverOptionsToken(resolver.use);
          providers.push({
            provide: resolver.use,
            useClass: resolver.use,
            inject: [optionsToken],
          });
          providers.push({
            provide: optionsToken,
            useFactory: () => resolver.options,
          });
        } else {
          const optionsToken = getI18nResolverOptionsToken(r as Function);
          providers.push({
            provide: r,
            useClass: r,
            inject: [optionsToken],
          } as any);
          providers.push({
            provide: optionsToken,
            useFactory: () => undefined,
          });
        }
 
        return providers;
      }, []);
  }
}