Skip to content
Open
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
40 changes: 40 additions & 0 deletions src/lib/components/HttpClient.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,4 +68,44 @@ describe('HttpClient', () => {
data: 'hello world',
});
});

it('should fetch and return status and data', async () => {
jest.spyOn(connection, 'request').mockReturnValue(
Promise.resolve({
status: 200,
data: 'hello world',
headers: {},
})
);

const response = await httpClient.fetch({
url: 'https://bigcontent.io',
method: HttpMethod.GET,
data: {},
});

expect(response).toEqual({
status: 200,
data: 'hello world',
});
});

it('should fetch and throw an error', async () => {
jest.spyOn(connection, 'request').mockReturnValue(
Promise.reject({
status: 404,
data: 'Not Found',
})
);

try {
await httpClient.fetch({
url: 'https://bigcontent.io',
method: HttpMethod.GET,
data: {},
});
} catch (error: any) {
expect(error.message).toBe('Request failed with status code 404');
}
});
});
17 changes: 17 additions & 0 deletions src/lib/components/HttpClient.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { ClientConnection } from 'message-event-channel';
import { HttpError } from './HttpError';

/**
* @hidden
Expand Down Expand Up @@ -88,4 +89,20 @@ export class HttpClient {
return this.DEFAULT_ERROR;
}
}

public async fetch(config: HttpRequest): Promise<HttpResponse> {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

perfect, would be good to get some basic docs down as well.

also DEFAULT_ERROR shows the shape of errors we normally return from API errors. unsure if we need to follow that shape here but looks good!

const response = await this.request(config);

return this.request(config).then((response: any) => {
if (response.status >= 200 && response.status < 300) {
return response;
} else {
throw new HttpError(
`Request failed with status code ${response.status}`,
config,
response
);
}
});
}
}
12 changes: 12 additions & 0 deletions src/lib/components/HttpError.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { HttpRequest, HttpResponse } from './HttpClient';

export class HttpError extends Error {
constructor(
message: string,
public readonly request?: HttpRequest,
public readonly response?: HttpResponse
) {
super(message);
Object.setPrototypeOf(this, new.target.prototype);
}
}