Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
5 changes: 5 additions & 0 deletions src/utils/proxy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ export interface ProxyOptions {
sendStream?: boolean;
cookieDomainRewrite?: string | Record<string, string>;
cookiePathRewrite?: string | Record<string, string>;
onResponse?: (event: H3Event) => void;
}

const PayloadMethods = new Set(["PATCH", "POST", "PUT", "DELETE"]);
Expand Down Expand Up @@ -105,6 +106,10 @@ export async function sendProxy(
event.node.res.setHeader(key, value);
}

if (opts.onResponse) {
await opts.onResponse(event);
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It would be also nice to pass over the actual response as second argument

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good idea, done!

}

// Directly send consumed _data
if ((response as any)._data !== undefined) {
return (response as any)._data;
Expand Down
49 changes: 49 additions & 0 deletions test/proxy.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -341,4 +341,53 @@ describe("", () => {
);
});
});

describe("onResponse", () => {
beforeEach(() => {
app.use(
"/debug",
eventHandler(() => {
return {};
})
);
});

it("allows modifying response event", async () => {
app.use(
"/",
eventHandler((event) => {
return proxyRequest(event, url + "/debug", {
fetch,
onResponse(_event) {
setHeader(_event, "x-custom", "hello");
},
});
})
);

const result = await request.get("/");

expect(result.header["x-custom"]).toEqual("hello");
});

it("allows modifying response event async", async () => {
app.use(
"/",
eventHandler((event) => {
return proxyRequest(event, url + "/debug", {
fetch,
onResponse(_event) {
return new Promise((resolve) => {
resolve(setHeader(_event, "x-custom", "hello"));
});
},
});
})
);

const result = await request.get("/");

expect(result.header["x-custom"]).toEqual("hello");
});
});
});