-
Notifications
You must be signed in to change notification settings - Fork 156
Expand file tree
/
Copy pathcookie.ts
More file actions
81 lines (66 loc) · 1.9 KB
/
cookie.ts
File metadata and controls
81 lines (66 loc) · 1.9 KB
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
import 'isomorphic-fetch';
import { IncomingMessage, ServerResponse } from 'http';
import isString from 'lodash/isString.js';
import cookie, { CookieSerializeOptions } from 'cookie';
import { base64Decode, base64Encode } from '../../utils/index.js';
export interface CookieOptions {
encoded?: boolean;
isJson?: boolean;
}
export class Cookies {
private request: IncomingMessage;
private response?: ServerResponse;
private cookies: Record<string, string> = {};
constructor(req: IncomingMessage, res?: ServerResponse) {
this.request = req;
this.response = res;
this.cookies = cookie.parse(this.request.headers.cookie || '');
}
public getCookie(
key: string,
options: CookieOptions & { isJson: true },
): any | undefined;
public getCookie(key: string, options?: CookieOptions): string | undefined;
public getCookie(
key: string,
{ encoded = true, isJson = false }: CookieOptions = {},
): string | any | undefined {
const value = this.cookies[key];
if (!isString(value)) {
return;
}
const valueStr = encoded ? base64Decode(value) : value;
// eslint-disable-next-line consistent-return
return isJson ? JSON.parse(valueStr) : valueStr;
}
public setCookie(
key: string,
value: string | Record<string, unknown>,
{
encoded = true,
isJson = false,
...serializeOptions
}: CookieOptions & CookieSerializeOptions = {},
): void {
const valueStr = isJson ? JSON.stringify(value) : (value as string);
const cookieValue = encoded ? base64Encode(valueStr) : valueStr;
this.cookies[key] = cookieValue;
this.response?.setHeader(
'Set-Cookie',
cookie.serialize(key, cookieValue, serializeOptions),
);
}
public removeCookie(key: string): void {
delete this.cookies[key];
this.response?.setHeader(
'Set-Cookie',
cookie.serialize(key, '', {
path: '/',
sameSite: 'strict',
secure: true,
httpOnly: true,
expires: new Date(0),
}),
);
}
}