Skip to content

Commit d23de20

Browse files
author
Simon Planinschek
committed
Add utility function for reading cookies form request objects
1 parent 1e3e398 commit d23de20

1 file changed

Lines changed: 20 additions & 1 deletion

File tree

src/utilities.ts

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@
44
*
55
* @param name { string } - Filter keyword
66
*/
7+
import { IncomingMessage } from 'http'
8+
79
const getCookiePattern = (name: string): RegExp => RegExp(name + '=.[^;]*')
810

911
/**
@@ -23,6 +25,23 @@ function getCookieFromDocument(name: string): string | undefined {
2325
return decodeURIComponent(cookie[1])
2426
}
2527

28+
function getCookieFromRequest(
29+
name: string,
30+
request: IncomingMessage
31+
): string | undefined {
32+
if (request.headers && request.headers.cookie) {
33+
const pattern = getCookiePattern(name)
34+
const matched = request.headers.cookie.match(pattern)
35+
36+
if (!matched) {
37+
return undefined
38+
}
39+
40+
const cookie = matched[0].split('=')
41+
return decodeURIComponent(cookie[1])
42+
}
43+
}
44+
2645
/**
2746
* Set new cookie
2847
*
@@ -46,4 +65,4 @@ function canUseDOM(): boolean {
4665
)
4766
}
4867

49-
export { getCookieFromDocument, setCookie, canUseDOM }
68+
export { getCookieFromDocument, getCookieFromRequest, setCookie, canUseDOM }

0 commit comments

Comments
 (0)