Skip to content

Commit

Permalink
feat: add support for resolvable headers (headers that can also be fu…
Browse files Browse the repository at this point in the history
…nctions)
  • Loading branch information
maxholman committed Oct 29, 2022
1 parent 8a00994 commit 5122b26
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 5 deletions.
7 changes: 6 additions & 1 deletion lib/fetcher.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,15 @@
import type { HttpMethod } from './generated/models.js';

export type ResolvableHeaders = Record<
string,
string | (() => string) | (() => Promise<string>)
>;

export type FetcherParams<T = unknown> = {
url: URL;
method: HttpMethod;
body?: T;
headers?: Record<string, string>;
headers?: ResolvableHeaders;
credentials?: 'include' | 'omit' | 'same-origin';
signal?: AbortSignal;
};
Expand Down
31 changes: 27 additions & 4 deletions src/isomorphic-fetch.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,44 @@
import ky from 'ky-universal';
import type { FetcherParams, FetcherResponse } from '../lib/fetcher.js';
import type {
FetcherParams,
FetcherResponse,
ResolvableHeaders,
} from '../lib/fetcher.js';

async function resolveHeaders(
headers: ResolvableHeaders | undefined,
): Promise<Record<string, string | undefined>> {
if (!headers) {
return {};
}

return Object.fromEntries(
await Promise.all(
Object.entries(headers).map(
async ([key, value]): Promise<[string, string]> => [
key,
value instanceof Function ? await value() : value,
],
),
),
);
}

export async function isomorphicFetcher<T>(
params: FetcherParams,
): Promise<FetcherResponse<T>> {
const { url, method, body, headers, credentials, signal } = params;

// const { keepAlive, } = options;
const resolvedHeaders = await resolveHeaders(headers);

const res = await ky(url, {
method,
throwHttpErrors: false,
...(headers && { headers }),
...(resolvedHeaders && { headers: resolvedHeaders }),
...(credentials && { credentials }),
...(!!body && { json: body }),
...(signal && { signal }),
// ...(keepAlive && { keepalive: keepAlive }),
timeout: 10000,
});

return {
Expand Down

0 comments on commit 5122b26

Please sign in to comment.