Skip to content

feat(client/sse): allow custom fetch implementation #296

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

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
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
13 changes: 11 additions & 2 deletions src/client/sse.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ export class SseError extends Error {
}
}

type FetchLike = (url: string | URL, init?: RequestInit) => Promise<Response>;

/**
* Configuration options for the `SSEClientTransport`.
*/
Expand Down Expand Up @@ -47,6 +49,11 @@ export type SSEClientTransportOptions = {
* Customizes recurring POST requests to the server.
*/
requestInit?: RequestInit;

/**
* Customizes the fetch implementation.
*/
fetch?: FetchLike;
};

/**
Expand All @@ -61,6 +68,7 @@ export class SSEClientTransport implements Transport {
private _eventSourceInit?: EventSourceInit;
private _requestInit?: RequestInit;
private _authProvider?: OAuthClientProvider;
private _fetch?: FetchLike;

onclose?: () => void;
onerror?: (error: Error) => void;
Expand All @@ -74,6 +82,7 @@ export class SSEClientTransport implements Transport {
this._eventSourceInit = opts?.eventSourceInit;
this._requestInit = opts?.requestInit;
this._authProvider = opts?.authProvider;
this._fetch = opts?.fetch;
}

private async _authThenStart(): Promise<void> {
Expand Down Expand Up @@ -113,7 +122,7 @@ export class SSEClientTransport implements Transport {
this._eventSource = new EventSource(
this._url.href,
this._eventSourceInit ?? {
fetch: (url, init) => this._commonHeaders().then((headers) => fetch(url, {
fetch: (url, init) => this._commonHeaders().then((headers) => (this._fetch ?? fetch)(url, {
...init,
headers: {
...headers,
Expand Down Expand Up @@ -222,7 +231,7 @@ export class SSEClientTransport implements Transport {
signal: this._abortController?.signal,
};

const response = await fetch(this._endpoint, init);
const response = await (this._fetch ?? fetch)(this._endpoint, init);
if (!response.ok) {
if (response.status === 401 && this._authProvider) {
const result = await auth(this._authProvider, { serverUrl: this._url });
Expand Down