Skip to content

Commit d665252

Browse files
committed
public API exposing parsed request cookies
1 parent 535f57d commit d665252

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed

src/Request.ts

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,11 @@ export class Request {
3232
*/
3333
public readonly ip: IPv4 | IPv6;
3434

35+
/**
36+
* The parsed request cookies from the {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Cookie|Cookie} request header.
37+
*/
38+
public readonly cookies: ReadonlyMap<string, string>;
39+
3540
/**
3641
* Construct a new Request.
3742
* @param method See {@link Request#method}.
@@ -52,6 +57,22 @@ export class Request {
5257
this.headers = headers;
5358
this.bodyStream = bodyStream;
5459
this.ip = ip;
60+
61+
this.cookies = new Map(
62+
this.headers.get("cookie")
63+
?.split("; ")
64+
.map(cookie => {
65+
const separatorIndex = cookie.indexOf("=");
66+
if (separatorIndex < 1)
67+
return null;
68+
const name = cookie.substring(0, separatorIndex);
69+
const value = cookie.substring(separatorIndex + 1);
70+
if (value.startsWith("\"") && value.endsWith("\""))
71+
return [name, value.substring(1, value.length - 1)];
72+
return [name, value];
73+
})
74+
.filter((cookie): cookie is [string, string] => cookie !== null)
75+
)
5576
}
5677

5778
/**

0 commit comments

Comments
 (0)