2017-09-19 13:32:04 -07:00
|
|
|
import fetch from 'fetch';
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Describes the attributes on the fetch configuration object
|
|
|
|
*/
|
|
|
|
interface FetchConfig {
|
|
|
|
url: string;
|
|
|
|
headers?: { [key: string]: string };
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Conveniently gets a JSON response using the fetch api
|
|
|
|
* @param {FetchConfig} config
|
|
|
|
* @return {Promise<T>}
|
|
|
|
*/
|
|
|
|
const getJSON = <T>(config: FetchConfig): Promise<T> => {
|
|
|
|
const fetchConfig = {
|
|
|
|
method: 'GET',
|
|
|
|
Accept: 'application/json',
|
|
|
|
'Content-Type': 'application/json',
|
|
|
|
...(config.headers || {})
|
|
|
|
};
|
|
|
|
|
|
|
|
return fetch(config.url, fetchConfig).then<T>(response => response.json());
|
|
|
|
};
|
|
|
|
|
2017-09-20 14:25:27 -07:00
|
|
|
/**
|
|
|
|
* Requests the headers from a resource endpoint
|
|
|
|
* @param {FetchConfig} config
|
2017-09-20 16:10:52 -07:00
|
|
|
* @return {Promise<Headers>>}
|
2017-09-20 14:25:27 -07:00
|
|
|
*/
|
2017-09-20 16:10:52 -07:00
|
|
|
const getHeaders = async (config: FetchConfig): Promise<Headers> => {
|
2017-09-20 14:25:27 -07:00
|
|
|
const fetchConfig = {
|
|
|
|
method: 'HEAD',
|
|
|
|
...(config.headers || {})
|
|
|
|
};
|
|
|
|
const { ok, headers, statusText } = await fetch(config.url, fetchConfig);
|
|
|
|
|
|
|
|
if (ok) {
|
2017-09-20 16:10:52 -07:00
|
|
|
return headers;
|
2017-09-20 14:25:27 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
throw new Error(statusText);
|
|
|
|
};
|
|
|
|
|
|
|
|
export { getJSON, getHeaders };
|