All files / lib/resolvers cookie.resolver.ts

100% Statements 21/21
86.67% Branches 13/15
100% Functions 2/2
100% Lines 19/19

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 465x 5x   5x           5x     3x           20x   18x 18x 18x   2x 2x     20x 20x 8x     20x 8x 8x 8x           12x      
import * as cookie from 'cookie';
import { Injectable, ExecutionContext } from '@nestjs/common';
import { I18nResolver } from '..';
import { I18nResolverOptions } from '../decorators/i18n-resolver-options.decorator';
 
/**
 * Simple resolver to fetch language/locale from cookie
 */
@Injectable()
export class CookieResolver implements I18nResolver {
  constructor(
    @I18nResolverOptions()
    private readonly cookieNames: string[] = ['lang'],
  ) {}
 
  resolve(context: ExecutionContext): string | string[] | undefined {
    let req: any;
 
    switch (context.getType() as string) {
      case 'http':
        req = context.switchToHttp().getRequest();
        req = req.raw ? req.raw : req;
        break;
      case 'graphql':
        [, , { req }] = context.getArgs();
        break;
    }
 
    Eif (req) {
      if (!req.cookies && req.headers.cookie) {
        req.cookies = cookie.parse(req.headers.cookie);
      }
 
      if (req.cookies) {
        for (const i in this.cookieNames) {
          Eif (req.cookies[this.cookieNames[i]]) {
            return req.cookies[this.cookieNames[i]];
          }
        }
      }
    }
 
    return undefined;
  }
}