mirror of
https://github.com/shlinkio/shlink-web-client.git
synced 2026-05-31 01:26:16 +00:00
Wrapped logic to perform HTTP requests with fetch into an HttpClient class
This commit is contained in:
21
src/common/services/HttpClient.ts
Normal file
21
src/common/services/HttpClient.ts
Normal file
@@ -0,0 +1,21 @@
|
||||
import { Fetch } from '../../utils/types';
|
||||
|
||||
export class HttpClient {
|
||||
constructor(private readonly fetch: Fetch) {}
|
||||
|
||||
public fetchJson<T>(url: string, options?: RequestInit): Promise<T> {
|
||||
return this.fetch(url, options).then(async (resp) => {
|
||||
const parsed = await resp.json();
|
||||
|
||||
if (!resp.ok) {
|
||||
throw parsed;
|
||||
}
|
||||
|
||||
return parsed as T;
|
||||
});
|
||||
}
|
||||
|
||||
public fetchBlob(url: string): Promise<Blob> {
|
||||
return this.fetch(url).then((resp) => resp.blob());
|
||||
}
|
||||
}
|
||||
@@ -1,11 +1,11 @@
|
||||
import { Fetch } from '../../utils/types';
|
||||
import { saveUrl } from '../../utils/helpers/files';
|
||||
import { HttpClient } from './HttpClient';
|
||||
|
||||
export class ImageDownloader {
|
||||
public constructor(private readonly fetch: Fetch, private readonly window: Window) {}
|
||||
public constructor(private readonly httpClient: HttpClient, private readonly window: Window) {}
|
||||
|
||||
public async saveImage(imgUrl: string, filename: string): Promise<void> {
|
||||
const data = await this.fetch(imgUrl).then((resp) => resp.blob());
|
||||
const data = await this.httpClient.fetchBlob(imgUrl);
|
||||
const url = URL.createObjectURL(data);
|
||||
|
||||
saveUrl(this.window, url, filename);
|
||||
|
||||
@@ -11,16 +11,16 @@ import { withoutSelectedServer } from '../../servers/helpers/withoutSelectedServ
|
||||
import { sidebarNotPresent, sidebarPresent } from '../reducers/sidebar';
|
||||
import { ImageDownloader } from './ImageDownloader';
|
||||
import { ReportExporter } from './ReportExporter';
|
||||
import { jsonFetch } from '../../utils/helpers/fetch';
|
||||
import { HttpClient } from './HttpClient';
|
||||
|
||||
const provideServices = (bottle: Bottle, connect: ConnectDecorator) => {
|
||||
// Services
|
||||
bottle.constant('window', (global as any).window);
|
||||
bottle.constant('console', global.console);
|
||||
bottle.constant('fetch', (global as any).fetch.bind(global));
|
||||
bottle.serviceFactory('jsonFetch', jsonFetch, 'fetch');
|
||||
|
||||
bottle.service('ImageDownloader', ImageDownloader, 'fetch', 'window');
|
||||
bottle.service('HttpClient', HttpClient, 'fetch');
|
||||
bottle.service('ImageDownloader', ImageDownloader, 'HttpClient', 'window');
|
||||
bottle.service('ReportExporter', ReportExporter, 'window', 'jsonToCsv');
|
||||
|
||||
// Components
|
||||
|
||||
Reference in New Issue
Block a user