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()]);
|
|
|
|
}
|
2019-07-28 16:49:02 +07:00
|
|
|
|
|
|
|
// unfortunatelly on download files there is no header available
|
|
|
|
if (response.url.match(/tgz/).length > 0) {
|
|
|
|
return Promise.all([response.ok, response.blob()]);
|
|
|
|
}
|
2019-06-20 19:37:28 +07:00
|
|
|
}
|
|
|
|
|
|
|
|
return Promise.resolve();
|
|
|
|
}
|
|
|
|
|
|
|
|
class API {
|
2019-07-28 16:49:02 +07:00
|
|
|
public request<T>(url: string, method = 'GET', options: RequestInit = { headers: {} }): 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-07-28 06:08:15 +07:00
|
|
|
if (token && options.headers && typeof options.headers['Authorization'] === 'undefined') {
|
|
|
|
options.headers = Object.assign({}, options.headers, {
|
|
|
|
['Authorization']: `Bearer ${token}`,
|
|
|
|
});
|
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)
|
2019-07-28 15:25:22 +07:00
|
|
|
.then(response => {
|
|
|
|
if (response[0]) {
|
|
|
|
resolve(response[1]);
|
2019-06-20 19:37:28 +07:00
|
|
|
} else {
|
2019-07-28 15:25:22 +07:00
|
|
|
reject(new Error('something went wrong'));
|
2019-06-20 19:37:28 +07:00
|
|
|
}
|
|
|
|
})
|
|
|
|
.catch(error => {
|
|
|
|
reject(error);
|
|
|
|
});
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
export default new API();
|