Skip to content

Commit

Permalink
feat(proxy): support onResponse callback (#368)
Browse files Browse the repository at this point in the history
  • Loading branch information
enkot authored Jun 20, 2023
1 parent 8a6c0ce commit 5a3d0e8
Show file tree
Hide file tree
Showing 2 changed files with 76 additions and 0 deletions.
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, response: Response) => void;
}

const PayloadMethods = new Set(["PATCH", "POST", "PUT", "DELETE"]);
Expand Down Expand Up @@ -112,6 +113,10 @@ export async function sendProxy(
);
}

if (opts.onResponse) {
await opts.onResponse(event, response);
}

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

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

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");
});

it("allows to get the actual response", async () => {
let proxyResponse;

app.use(
"/",
eventHandler((event) => {
return proxyRequest(event, url + "/debug", {
fetch,
async onResponse(_event, response) {
proxyResponse = await response.json();
},
});
})
);

await request.get("/");

expect(proxyResponse).toEqual({ foo: "bar" });
});
});
});

0 comments on commit 5a3d0e8

Please sign in to comment.