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: fetchWithEvent and getProxyRequestHeaders utils #323

Merged
merged 3 commits into from
Feb 8, 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
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,8 @@ H3 has a concept of composable utilities that accept `event` (from `eventHandler
- `createError({ statusCode, statusMessage, data? })`
- `sendProxy(event, { target, headers?, fetchOptions?, fetch?, sendStream? })`
- `proxyRequest(event, { target, headers?, fetchOptions?, fetch?, sendStream? })`
- `fetchWithEvent(event, req, init, { fetch? }?)`
- `getProxyRequestHeaders(event)`
- `sendNoContent(event, code = 204)`
- `setResponseStatus(event, status)`
- `getResponseStatus(event)`
Expand Down
81 changes: 55 additions & 26 deletions src/utils/proxy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,13 +35,7 @@ export async function proxyRequest(
}

// Headers
const headers = Object.create(null);
const reqHeaders = getRequestHeaders(event);
for (const name in reqHeaders) {
if (!ignoredHeaders.has(name)) {
headers[name] = reqHeaders[name];
}
}
const headers = getProxyRequestHeaders(event);
if (opts.fetchOptions?.headers) {
Object.assign(headers, opts.fetchOptions.headers);
}
Expand All @@ -65,14 +59,7 @@ export async function sendProxy(
target: string,
opts: ProxyOptions = {}
) {
const _fetch = opts.fetch || globalThis.fetch;
if (!_fetch) {
throw new Error(
"fetch is not available. Try importing `node-fetch-native/polyfill` for Node.js."
);
}

const response = await _fetch(target, {
const response = await _getFetch(opts.fetch)(target, {
headers: opts.headers as HeadersInit,
...opts.fetchOptions,
});
Expand All @@ -90,19 +77,61 @@ export async function sendProxy(
}

try {
if (response.body) {
if (opts.sendStream === false) {
const data = new Uint8Array(await response.arrayBuffer());
event.node.res.end(data);
} else {
for await (const chunk of response.body as any as AsyncIterable<Uint8Array>) {
event.node.res.write(chunk);
}
event.node.res.end();
}
if ((response as any)._data) {
return event.node.res.end((response as any)._data);
}
if (opts.sendStream === false) {
const data = new Uint8Array(await response.arrayBuffer());
return event.node.res.end(data);
}
for await (const chunk of response.body as any as AsyncIterable<Uint8Array>) {
event.node.res.write(chunk);
}
} catch (error) {
event.node.res.end();
} catch (error) {
event.node.res.end((response as any)._data);
throw error;
}
}

export function getProxyRequestHeaders(event: H3Event) {
const headers = Object.create(null);
const reqHeaders = getRequestHeaders(event);
for (const name in reqHeaders) {
if (!ignoredHeaders.has(name)) {
headers[name] = reqHeaders[name];
}
}
return headers;
}

export function fetchWithEvent(
event: H3Event,
req: RequestInfo,
init?: RequestInit,
options?: { fetch: typeof fetch }
) {
return _getFetch(options?.fetch)(req, {
...init,
// @ts-ignore (context is used for unenv and local fetch)
context: init.context || event.context,
headers: {
...getProxyRequestHeaders(event),
...init?.headers,
},
});
}

// -- internal utils --

function _getFetch(_fetch?: typeof fetch) {
if (_fetch) {
return _fetch;
}
if (globalThis.fetch) {
return globalThis.fetch;
}
throw new Error(
"fetch is not available. Try importing `node-fetch-native/polyfill` for Node.js."
);
}