Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(event): support event.url #455

Merged
merged 1 commit into from
Jul 24, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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/);
});
});