Replace local ShlinkApiClient with the one from shlink-js-sdk

This commit is contained in:
Alejandro Celaya
2023-08-29 23:12:25 +02:00
parent ccfedc20e9
commit 9f7ac09fb0
14 changed files with 62 additions and 745 deletions

View File

@@ -1,46 +0,0 @@
type Fetch = typeof window.fetch;
export type RequestOptions = {
method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
body?: string;
headers?: Record<string, string>;
};
const applicationJsonHeader = { 'Content-Type': 'application/json' };
const withJsonContentType = (options?: RequestOptions): RequestInit | undefined => {
if (!options?.body) {
return options;
}
return options ? {
...options,
headers: {
...(options.headers ?? {}),
...applicationJsonHeader,
},
} : {
headers: applicationJsonHeader,
};
};
export class HttpClient {
constructor(private readonly fetch: Fetch) {}
public readonly fetchJson = <T>(url: string, options?: RequestOptions): Promise<T> =>
this.fetch(url, withJsonContentType(options)).then(async (resp) => {
const json = await resp.json();
if (!resp.ok) {
throw json;
}
return json as T;
});
public readonly fetchEmpty = (url: string, options?: RequestOptions): Promise<void> =>
this.fetch(url, withJsonContentType(options)).then(async (resp) => {
if (!resp.ok) {
throw await resp.json();
}
});
}

View File

@@ -1,3 +1,4 @@
import { FetchHttpClient } from '@shlinkio/shlink-js-sdk/browser';
import { ShlinkWebComponent } from '@shlinkio/shlink-web-component';
import type Bottle from 'bottlejs';
import type { ConnectDecorator } from '../../container/types';
@@ -8,14 +9,13 @@ import { MainHeader } from '../MainHeader';
import { ScrollToTop } from '../ScrollToTop';
import { ShlinkVersionsContainer } from '../ShlinkVersionsContainer';
import { ShlinkWebComponentContainer } from '../ShlinkWebComponentContainer';
import { HttpClient } from './HttpClient';
export const provideServices = (bottle: Bottle, connect: ConnectDecorator) => {
// Services
bottle.constant('window', window);
bottle.constant('console', console);
bottle.constant('fetch', window.fetch.bind(window));
bottle.service('HttpClient', HttpClient, 'fetch');
bottle.service('HttpClient', FetchHttpClient, 'fetch');
// Components
bottle.serviceFactory('ScrollToTop', () => ScrollToTop);