2021-03-26 04:17:02 +04:30
|
|
|
/*
|
|
|
|
|
* Copyright (C) Contributors to the Suwayomi project
|
|
|
|
|
*
|
|
|
|
|
* This Source Code Form is subject to the terms of the Mozilla Public
|
2021-03-07 22:25:29 +03:30
|
|
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
|
|
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
|
|
|
|
|
|
2021-03-07 16:27:13 +03:30
|
|
|
import axios from 'axios';
|
2021-03-07 22:25:29 +03:30
|
|
|
import storage from './localStorage';
|
|
|
|
|
|
|
|
|
|
const { hostname, port, protocol } = window.location;
|
2021-03-07 16:27:13 +03:30
|
|
|
|
2021-03-07 22:25:29 +03:30
|
|
|
// if port is 3000 it's probably running from webpack devlopment server
|
|
|
|
|
let inferredPort;
|
|
|
|
|
if (port === '3000') { inferredPort = '4567'; } else { inferredPort = port; }
|
|
|
|
|
|
2022-11-02 10:42:02 +01:00
|
|
|
const baseURL = storage.getItem('serverBaseURL', `${protocol}//${hostname}:${inferredPort}`);
|
|
|
|
|
|
2021-03-07 22:25:29 +03:30
|
|
|
const client = axios.create({
|
|
|
|
|
// baseURL must not have traling slash
|
2022-11-02 10:42:02 +01:00
|
|
|
baseURL,
|
2021-03-07 16:27:13 +03:30
|
|
|
});
|
|
|
|
|
|
2021-03-07 22:25:29 +03:30
|
|
|
client.interceptors.request.use((config) => {
|
|
|
|
|
if (config.data instanceof FormData) {
|
|
|
|
|
Object.assign(config.headers, { 'Content-Type': 'multipart/form-data' });
|
|
|
|
|
}
|
|
|
|
|
return config;
|
|
|
|
|
});
|
2021-03-07 16:27:13 +03:30
|
|
|
|
|
|
|
|
export default client;
|
2022-11-02 10:42:02 +01:00
|
|
|
|
|
|
|
|
export async function fetcher<T = any>(path: string) {
|
|
|
|
|
const res = await client.get(path);
|
|
|
|
|
if (res.status !== 200) {
|
|
|
|
|
throw new Error(res.statusText);
|
|
|
|
|
}
|
|
|
|
|
if (res.headers['content-type'] !== 'application/json') {
|
|
|
|
|
throw new Error('Response is not json');
|
|
|
|
|
}
|
|
|
|
|
return res.data as T;
|
|
|
|
|
}
|