Skip to content

Commit f7bfc72

Browse files
authored
Parse request URL path components (#49)
2 parents bccb882 + 1606c86 commit f7bfc72

File tree

1 file changed

+20
-2
lines changed

1 file changed

+20
-2
lines changed

src/Request.ts

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,11 @@ export class Request<A> {
4141
*/
4242
public readonly server: Server<A>;
4343

44+
/**
45+
* The components of the request URL path name.
46+
*/
47+
public readonly pathComponents: ReadonlyArray<string>;
48+
4449
/**
4550
* The parsed request cookies from the {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Cookie|Cookie} request header.
4651
*/
@@ -54,6 +59,7 @@ export class Request<A> {
5459
* @param bodyStream See {@link Request#bodyStream}.
5560
* @param ip See {@link Request#ip}.
5661
* @param server See {@link Request#server}.
62+
* @throws {@link !URIError} If the request URL path name contains an invalid URI escape sequence.
5763
*/
5864
public constructor(
5965
method: Request<A>["method"],
@@ -70,6 +76,11 @@ export class Request<A> {
7076
this.ip = ip;
7177
this.server = server;
7278

79+
this.pathComponents = this.url.pathname
80+
.split("/")
81+
.map(decodeURIComponent)
82+
.filter(component => component.length > 0);
83+
7384
this.cookies = new Map(
7485
this.headers.get("cookie")
7586
?.split("; ")
@@ -113,7 +124,14 @@ export class Request<A> {
113124
if (remoteAddress === undefined)
114125
throw new Request.SocketClosedError();
115126

116-
return new Request<A>(incomingMessage.method as Request.Method, new URL(url), headers, incomingMessage, IPAddress.fromString(remoteAddress), server);
127+
try {
128+
return new Request<A>(incomingMessage.method as Request.Method, new URL(url), headers, incomingMessage, IPAddress.fromString(remoteAddress), server);
129+
}
130+
catch (e) {
131+
if (e instanceof URIError)
132+
throw new Request.BadUrlError(incomingMessage.url);
133+
throw e;
134+
}
117135
}
118136

119137
/**
@@ -241,7 +259,7 @@ export class Request<A> {
241259
export namespace Request {
242260
export class BadUrlError extends Error {
243261
public constructor(public readonly path: string | undefined) {
244-
super(`${path} is not a valid URL.`);
262+
super(`${path} is not a valid URL or contains invalid URI escape sequences.`);
245263
}
246264
}
247265

0 commit comments

Comments
 (0)