Migrated ImageDownloader from axios to fetch

This commit is contained in:
Alejandro Celaya 2022-11-15 11:41:05 +01:00
parent a88ebc26a9
commit 34aa156d5f
9 changed files with 21 additions and 31 deletions

View file

@ -20,7 +20,7 @@ import {
import { orderToString } from '../../utils/helpers/ordering'; import { orderToString } from '../../utils/helpers/ordering';
import { isRegularNotFound, parseApiError } from '../utils'; import { isRegularNotFound, parseApiError } from '../utils';
import { stringifyQuery } from '../../utils/helpers/query'; import { stringifyQuery } from '../../utils/helpers/query';
import { Fetch } from '../../utils/types'; import { JsonFetch } from '../../utils/types';
const buildShlinkBaseUrl = (url: string, version: 2 | 3) => `${url}/rest/v${version}`; const buildShlinkBaseUrl = (url: string, version: 2 | 3) => `${url}/rest/v${version}`;
const rejectNilProps = reject(isNil); const rejectNilProps = reject(isNil);
@ -34,7 +34,7 @@ export class ShlinkApiClient {
private apiVersion: 2 | 3; private apiVersion: 2 | 3;
public constructor( public constructor(
private readonly fetch: Fetch, private readonly fetch: JsonFetch,
private readonly baseUrl: string, private readonly baseUrl: string,
private readonly apiKey: string, private readonly apiKey: string,
) { ) {

View file

@ -1,7 +1,7 @@
import { hasServerData, ServerWithId } from '../../servers/data'; import { hasServerData, ServerWithId } from '../../servers/data';
import { GetState } from '../../container/types'; import { GetState } from '../../container/types';
import { ShlinkApiClient } from './ShlinkApiClient'; import { ShlinkApiClient } from './ShlinkApiClient';
import { Fetch } from '../../utils/types'; import { JsonFetch } from '../../utils/types';
const apiClients: Record<string, ShlinkApiClient> = {}; const apiClients: Record<string, ShlinkApiClient> = {};
@ -16,7 +16,7 @@ const getSelectedServerFromState = (getState: GetState): ServerWithId => {
return selectedServer; return selectedServer;
}; };
export const buildShlinkApiClient = (fetch: Fetch) => (getStateOrSelectedServer: GetState | ServerWithId) => { export const buildShlinkApiClient = (fetch: JsonFetch) => (getStateOrSelectedServer: GetState | ServerWithId) => {
const { url, apiKey } = isGetState(getStateOrSelectedServer) const { url, apiKey } = isGetState(getStateOrSelectedServer)
? getSelectedServerFromState(getStateOrSelectedServer) ? getSelectedServerFromState(getStateOrSelectedServer)
: getStateOrSelectedServer; : getStateOrSelectedServer;

View file

@ -1,4 +1,3 @@
import { AxiosError } from 'axios';
import { import {
ErrorTypeV2, ErrorTypeV2,
ErrorTypeV3, ErrorTypeV3,
@ -11,15 +10,7 @@ import {
const isProblemDetails = (e: unknown): e is ProblemDetailsError => const isProblemDetails = (e: unknown): e is ProblemDetailsError =>
!!e && typeof e === 'object' && Object.keys(e).every((key) => ['type', 'detail', 'title', 'status'].includes(key)); !!e && typeof e === 'object' && Object.keys(e).every((key) => ['type', 'detail', 'title', 'status'].includes(key));
const isAxiosError = (e: unknown): e is AxiosError<ProblemDetailsError> => !!e && typeof e === 'object' && 'response' in e; export const parseApiError = (e: unknown): ProblemDetailsError | undefined => (isProblemDetails(e) ? e : undefined);
export const parseApiError = (e: unknown): ProblemDetailsError | undefined => {
if (isProblemDetails(e)) {
return e;
}
return (isAxiosError(e) ? e.response?.data : undefined);
};
export const isInvalidArgumentError = (error?: ProblemDetailsError): error is InvalidArgumentError => export const isInvalidArgumentError = (error?: ProblemDetailsError): error is InvalidArgumentError =>
error?.type === ErrorTypeV2.INVALID_ARGUMENT || error?.type === ErrorTypeV3.INVALID_ARGUMENT; error?.type === ErrorTypeV2.INVALID_ARGUMENT || error?.type === ErrorTypeV3.INVALID_ARGUMENT;

View file

@ -1,11 +1,11 @@
import { AxiosInstance } from 'axios'; import { Fetch } from '../../utils/types';
import { saveUrl } from '../../utils/helpers/files'; import { saveUrl } from '../../utils/helpers/files';
export class ImageDownloader { export class ImageDownloader {
public constructor(private readonly axios: AxiosInstance, private readonly window: Window) {} public constructor(private readonly fetch: Fetch, private readonly window: Window) {}
public async saveImage(imgUrl: string, filename: string): Promise<void> { public async saveImage(imgUrl: string, filename: string): Promise<void> {
const { data } = await this.axios.get(imgUrl, { responseType: 'blob' }); const data = await this.fetch(imgUrl).then((resp) => resp.blob());
const url = URL.createObjectURL(data); const url = URL.createObjectURL(data);
saveUrl(this.window, url, filename); saveUrl(this.window, url, filename);

View file

@ -19,10 +19,10 @@ const provideServices = (bottle: Bottle, connect: ConnectDecorator) => {
bottle.constant('window', (global as any).window); bottle.constant('window', (global as any).window);
bottle.constant('console', global.console); bottle.constant('console', global.console);
bottle.constant('axios', axios); bottle.constant('axios', axios);
bottle.constant('fetch', (global as any).fetch.bind((global as any))); bottle.constant('fetch', (global as any).fetch.bind(global));
bottle.serviceFactory('jsonFetch', jsonFetch, 'fetch'); bottle.serviceFactory('jsonFetch', jsonFetch, 'fetch');
bottle.service('ImageDownloader', ImageDownloader, 'axios', 'window'); bottle.service('ImageDownloader', ImageDownloader, 'fetch', 'window');
bottle.service('ReportExporter', ReportExporter, 'window', 'jsonToCsv'); bottle.service('ReportExporter', ReportExporter, 'window', 'jsonToCsv');
// Components // Components

View file

@ -2,11 +2,11 @@ import pack from '../../../package.json';
import { hasServerData, ServerData } from '../data'; import { hasServerData, ServerData } from '../data';
import { createServers } from './servers'; import { createServers } from './servers';
import { createAsyncThunk } from '../../utils/helpers/redux'; import { createAsyncThunk } from '../../utils/helpers/redux';
import { Fetch } from '../../utils/types'; import { JsonFetch } from '../../utils/types';
const responseToServersList = (data: any): ServerData[] => (Array.isArray(data) ? data.filter(hasServerData) : []); const responseToServersList = (data: any): ServerData[] => (Array.isArray(data) ? data.filter(hasServerData) : []);
export const fetchServers = (fetch: Fetch) => createAsyncThunk( export const fetchServers = (fetch: JsonFetch) => createAsyncThunk(
'shlink/remoteServers/fetchServers', 'shlink/remoteServers/fetchServers',
async (_: void, { dispatch }): Promise<void> => { async (_: void, { dispatch }): Promise<void> => {
const resp = await fetch<any>(`${pack.homepage}/servers.json`); const resp = await fetch<any>(`${pack.homepage}/servers.json`);

View file

@ -1,3 +1,5 @@
export type MediaMatcher = (query: string) => MediaQueryList; export type MediaMatcher = (query: string) => MediaQueryList;
export type Fetch = <T>(url: string, options?: RequestInit) => Promise<T>; export type Fetch = typeof window.fetch;
export type JsonFetch = <T>(url: string, options?: RequestInit) => Promise<T>;

View file

@ -3,12 +3,12 @@ import { ShlinkApiClient } from '../../../src/api/services/ShlinkApiClient';
import { OptionalString } from '../../../src/utils/utils'; import { OptionalString } from '../../../src/utils/utils';
import { ShlinkDomain, ShlinkVisits, ShlinkVisitsOverview } from '../../../src/api/types'; import { ShlinkDomain, ShlinkVisits, ShlinkVisitsOverview } from '../../../src/api/types';
import { ShortUrl, ShortUrlsOrder } from '../../../src/short-urls/data'; import { ShortUrl, ShortUrlsOrder } from '../../../src/short-urls/data';
import { Fetch } from '../../../src/utils/types'; import { JsonFetch } from '../../../src/utils/types';
describe('ShlinkApiClient', () => { describe('ShlinkApiClient', () => {
const buildFetch = (data: any) => jest.fn().mockResolvedValue(data); const buildFetch = (data: any) => jest.fn().mockResolvedValue(data);
const buildRejectedFetch = (error: any) => jest.fn().mockRejectedValueOnce(error); const buildRejectedFetch = (error: any) => jest.fn().mockRejectedValueOnce(error);
const buildApiClient = (fetch: Fetch) => new ShlinkApiClient(fetch, '', ''); const buildApiClient = (fetch: JsonFetch) => new ShlinkApiClient(fetch, '', '');
const shortCodesWithDomainCombinations: [string, OptionalString][] = [ const shortCodesWithDomainCombinations: [string, OptionalString][] = [
['abc123', null], ['abc123', null],
['abc123', undefined], ['abc123', undefined],

View file

@ -1,25 +1,22 @@
import { Mock } from 'ts-mockery';
import { AxiosInstance } from 'axios';
import { ImageDownloader } from '../../../src/common/services/ImageDownloader'; import { ImageDownloader } from '../../../src/common/services/ImageDownloader';
import { windowMock } from '../../__mocks__/Window.mock'; import { windowMock } from '../../__mocks__/Window.mock';
describe('ImageDownloader', () => { describe('ImageDownloader', () => {
const get = jest.fn(); const fetch = jest.fn();
const axios = Mock.of<AxiosInstance>({ get });
let imageDownloader: ImageDownloader; let imageDownloader: ImageDownloader;
beforeEach(() => { beforeEach(() => {
jest.clearAllMocks(); jest.clearAllMocks();
(global as any).URL = { createObjectURL: () => '' }; (global as any).URL = { createObjectURL: () => '' };
imageDownloader = new ImageDownloader(axios, windowMock); imageDownloader = new ImageDownloader(fetch, windowMock);
}); });
it('calls URL with response type blob', async () => { it('calls URL with response type blob', async () => {
get.mockResolvedValue({ data: {} }); fetch.mockResolvedValue({ blob: () => new Blob() });
await imageDownloader.saveImage('/foo/bar.png', 'my-image.png'); await imageDownloader.saveImage('/foo/bar.png', 'my-image.png');
expect(get).toHaveBeenCalledWith('/foo/bar.png', { responseType: 'blob' }); expect(fetch).toHaveBeenCalledWith('/foo/bar.png');
}); });
}); });