diff --git a/src/lib/components/HttpClient.spec.ts b/src/lib/components/HttpClient.spec.ts index 8981e44..116dade 100644 --- a/src/lib/components/HttpClient.spec.ts +++ b/src/lib/components/HttpClient.spec.ts @@ -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'); + } + }); }); diff --git a/src/lib/components/HttpClient.ts b/src/lib/components/HttpClient.ts index c63422b..b246e89 100644 --- a/src/lib/components/HttpClient.ts +++ b/src/lib/components/HttpClient.ts @@ -1,4 +1,5 @@ import { ClientConnection } from 'message-event-channel'; +import { HttpError } from './HttpError'; /** * @hidden @@ -88,4 +89,20 @@ export class HttpClient { return this.DEFAULT_ERROR; } } + + public async fetch(config: HttpRequest): Promise { + 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 + ); + } + }); + } } diff --git a/src/lib/components/HttpError.ts b/src/lib/components/HttpError.ts new file mode 100644 index 0000000..508885c --- /dev/null +++ b/src/lib/components/HttpError.ts @@ -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); + } +}