2019-06-20 19:37:28 +07:00
|
|
|
import storage from './storage';
|
|
|
|
import '../../types';
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Handles response according to content type
|
|
|
|
* @param {object} response
|
|
|
|
* @returns {promise}
|
|
|
|
*/
|
2019-06-22 16:43:59 +07:00
|
|
|
function handleResponseType(response: Response): Promise<[boolean, Blob | string]> | Promise<void> {
|
2019-06-20 19:37:28 +07:00
|
|
|
if (response.headers) {
|
2019-06-22 16:43:59 +07:00
|
|
|
const contentType = response.headers.get('Content-Type') as string;
|
2019-06-20 19:37:28 +07:00
|
|
|
if (contentType.includes('application/pdf')) {
|
|
|
|
return Promise.all([response.ok, response.blob()]);
|
|
|
|
}
|
|
|
|
if (contentType.includes('application/json')) {
|
|
|
|
return Promise.all([response.ok, response.json()]);
|
|
|
|
}
|
|
|
|
// it includes all text types
|
|
|
|
if (contentType.includes('text/')) {
|
|
|
|
return Promise.all([response.ok, response.text()]);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return Promise.resolve();
|
|
|
|
}
|
|
|
|
|
|
|
|
class API {
|
2019-06-24 02:50:30 +07:00
|
|
|
public request<T>(url: string, method = 'GET', options?: RequestInit): Promise<T> {
|
2019-06-20 19:37:28 +07:00
|
|
|
if (!window.VERDACCIO_API_URL) {
|
|
|
|
throw new Error('VERDACCIO_API_URL is not defined!');
|
|
|
|
}
|
|
|
|
|
|
|
|
const token = storage.getItem('token');
|
2019-06-24 02:50:30 +07:00
|
|
|
const headers = new Headers(options && options.headers);
|
|
|
|
if (token && options && options.headers) {
|
|
|
|
headers.set('Authorization', `Bearer ${token}`);
|
|
|
|
options.headers = Object.assign(options.headers, headers);
|
2019-06-20 19:37:28 +07:00
|
|
|
}
|
|
|
|
|
|
|
|
if (!['http://', 'https://', '//'].some(prefix => url.startsWith(prefix))) {
|
|
|
|
// @ts-ignore
|
|
|
|
url = window.VERDACCIO_API_URL + url;
|
|
|
|
}
|
|
|
|
|
2019-06-24 02:50:30 +07:00
|
|
|
return new Promise((resolve, reject) => {
|
2019-06-20 19:37:28 +07:00
|
|
|
fetch(url, {
|
|
|
|
method,
|
|
|
|
credentials: 'same-origin',
|
|
|
|
...options,
|
|
|
|
})
|
|
|
|
// @ts-ignore
|
|
|
|
.then(handleResponseType)
|
|
|
|
.then(([responseOk, body]) => {
|
|
|
|
if (responseOk) {
|
|
|
|
resolve(body);
|
|
|
|
} else {
|
|
|
|
reject(body);
|
|
|
|
}
|
|
|
|
})
|
|
|
|
.catch(error => {
|
|
|
|
reject(error);
|
|
|
|
});
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
export default new API();
|