Skip to content

Commit

Permalink
feat(event): support event.url (#455)
Browse files Browse the repository at this point in the history
  • Loading branch information
pi0 authored Jul 24, 2023
1 parent 356fa28 commit a9b8de8
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 2 deletions.
15 changes: 14 additions & 1 deletion src/event/event.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
import type { IncomingHttpHeaders } from "node:http";
import type { H3EventContext, HTTPMethod } from "../types";
import type { NodeIncomingMessage, NodeServerResponse } from "../node";
import { MIMES, sanitizeStatusCode, sanitizeStatusMessage } from "../utils";
import {
MIMES,
getRequestURL,
sanitizeStatusCode,
sanitizeStatusMessage,
} from "../utils";
import { H3Response } from "./response";

const DOUBLE_SLASH_RE = /[/\\]{2,}/g; // TODO: Dedup from request.ts
Expand All @@ -22,6 +27,7 @@ export class H3Event implements Pick<FetchEvent, "respondWith"> {
_method: HTTPMethod | undefined;
_headers: Headers | undefined;
_path: string | undefined;
_url: URL | undefined;

// Response
_handled = false;
Expand All @@ -45,6 +51,13 @@ export class H3Event implements Pick<FetchEvent, "respondWith"> {
return this._path;
}

get url() {
if (!this._url) {
this._url = getRequestURL(this);
}
return this._url;
}

get handled(): boolean {
return (
this._handled || this.node.res.writableEnded || this.node.res.headersSent
Expand Down
2 changes: 1 addition & 1 deletion src/utils/request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,6 @@ export function getRequestURL(
) {
const host = getRequestHost(event, opts);
const protocol = getRequestProtocol(event);
const path = getRequestPath(event);
const path = event.path;
return new URL(path, `${protocol}://${host}`);
}
11 changes: 11 additions & 0 deletions test/event.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,4 +49,15 @@ describe("Event", () => {
expect(headers.find(([key]) => key === "x-test")[1]).toBe("works");
expect(headers.find(([key]) => key === "cookie")[1]).toBe("a; b");
});

it("can get request url", async () => {
app.use(
"/",
eventHandler((event) => {
return event.url;
})
);
const result = await request.get("/hello");
expect(result.text).toMatch(/http:\/\/127.0.0.1:\d+\/hello/);
});
});

0 comments on commit a9b8de8

Please sign in to comment.