-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutilities.ts
More file actions
68 lines (58 loc) · 1.6 KB
/
Copy pathutilities.ts
File metadata and controls
68 lines (58 loc) · 1.6 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
/**
* Regex based filter to get cookie values
* This includes the =
*
* @param name { string } - Filter keyword
*/
import { IncomingMessage } from 'http'
const getCookiePattern = (name: string): RegExp => RegExp(name + '=.[^;]*')
/**
* Get cookie from document (Local DOM)
*
* @param name { string } - Cookie name
*/
function getCookieFromDocument(name: string): string | undefined {
const pattern = getCookiePattern(name)
const matched = document.cookie.match(pattern)
if (!matched) {
return undefined
}
const cookie = matched[0].split('=')
return decodeURIComponent(cookie[1])
}
function getCookieFromRequest(
name: string,
request: IncomingMessage
): string | undefined {
if (request.headers && request.headers.cookie) {
const pattern = getCookiePattern(name)
const matched = request.headers.cookie.match(pattern)
if (!matched) {
return undefined
}
const cookie = matched[0].split('=')
return decodeURIComponent(cookie[1])
}
}
/**
* Set new cookie
*
* @param name { string } - Cookie name
* @param value { string } - Cookie value
*/
function setCookie(name: string, value: string): void {
document.cookie = name + '=' + value + ';path=/'
}
/**
* Check if the DOM is available
* if this function returns false, it means that the page is not rendered by the client.
* However, it might be pre-rendered for example on a server.
*/
function canUseDOM(): boolean {
return !!(
typeof window != 'undefined' &&
window.document &&
window.document.createElement
)
}
export { getCookieFromDocument, getCookieFromRequest, setCookie, canUseDOM }