-
Notifications
You must be signed in to change notification settings - Fork 103
/
cookie.resolver.ts
45 lines (39 loc) · 1.1 KB
/
cookie.resolver.ts
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
import * as cookie from 'cookie';
import { Injectable, ExecutionContext } from '@nestjs/common';
import { I18nResolver } from '..';
import { I18nResolverOptions } from '../decorators';
/**
* 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;
}
if (req) {
if (!req.cookies && req.headers.cookie) {
req.cookies = cookie.parse(req.headers.cookie);
}
if (req.cookies) {
for (const i in this.cookieNames) {
if (req.cookies[this.cookieNames[i]]) {
return req.cookies[this.cookieNames[i]];
}
}
}
}
return undefined;
}
}