Skip to content

Commit

Permalink
Merge pull request #13 from chadsr/feature/custom-fetch
Browse files Browse the repository at this point in the history
feature: support custom fetch implementation
  • Loading branch information
lukas-reining authored Sep 5, 2024
2 parents c294aae + 6e310f7 commit 8a095bd
Show file tree
Hide file tree
Showing 4 changed files with 32 additions and 4 deletions.
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "extended-eventsource",
"version": "1.4.9",
"version": "1.5.0",
"author": "Lukas Reining",
"readme": "README.md",
"description": "Spec compliant EventSource implementation for browsers and Node.JS",
Expand Down
24 changes: 24 additions & 0 deletions src/eventsource.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,30 @@ describe('EventSource', () => {
ev.onopen = () => done();
});

it('allows for a custom fetch implementation to be used', (done) => {
mockChunks();

const fetchFn = jest.fn((input, init?) => {
return globalThis.fetch(input, init);
}) as typeof fetch;

const ev = new EventSource(
'http://localhost/sse',
{
disableRetry: true,
},
{
inputFetch: fetchFn,
},
);

ev.onopen = (event) => {
expect(event).toBeInstanceOf(Event);
expect(fetchFn).toHaveBeenCalled();
done();
};
});

it('fails fatally if wrong content type is returned', (done) => {
server.use(
http.get('http://localhost/sse', () => {
Expand Down
6 changes: 5 additions & 1 deletion src/eventsource.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,11 +40,15 @@ export class CustomEventSource extends EventTarget implements EventSource {

private logger?: Logger;

private fetch: typeof fetch;

constructor(
url: string | URL,
initDict?: EventSourceInit & EventSourceOptions,
{ inputFetch } = { inputFetch: globalThis.fetch },
) {
super();
this.fetch = inputFetch;
this.url = url instanceof URL ? url.toString() : url;
this.options = initDict ?? {};
this.retry = initDict?.retry ?? 5000;
Expand Down Expand Up @@ -95,7 +99,7 @@ export class CustomEventSource extends EventTarget implements EventSource {
signal: this.abortController?.signal,
};

const response = await globalThis.fetch(this.url, fetchOptions);
const response = await this.fetch(this.url, fetchOptions);

// https://html.spec.whatwg.org/multipage/server-sent-events.html#dom-eventsource (Step 15)
if (response.status !== 200) {
Expand Down

0 comments on commit 8a095bd

Please sign in to comment.