2022-02-15 20:33:31 -07:00
|
|
|
'use strict';
|
|
|
|
|
2022-02-10 00:42:02 -07:00
|
|
|
const fetch = require('node-fetch');
|
|
|
|
|
|
|
|
class HTTPResponseError extends Error {
|
|
|
|
constructor(response, responseText, ...args) {
|
|
|
|
super(
|
|
|
|
`HTTP Error Response: ${response.status} ${response.statusText}: ${responseText}\n URL=${response.url}`,
|
|
|
|
...args
|
|
|
|
);
|
|
|
|
this.response = response;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
const checkResponseStatus = async (response) => {
|
|
|
|
if (response.ok) {
|
|
|
|
// response.status >= 200 && response.status < 300
|
|
|
|
return response;
|
|
|
|
} else {
|
|
|
|
const responseText = await response.text();
|
|
|
|
throw new HTTPResponseError(response, responseText);
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2022-02-23 20:25:05 -07:00
|
|
|
async function fetchEndpoint(endpoint, options = {}) {
|
|
|
|
const { method, accessToken } = options;
|
|
|
|
const headers = options.headers || {};
|
|
|
|
|
|
|
|
if (accessToken) {
|
|
|
|
headers.Authorization = `Bearer ${accessToken}`;
|
|
|
|
}
|
|
|
|
|
2022-02-10 00:42:02 -07:00
|
|
|
const res = await fetch(endpoint, {
|
2022-02-23 20:25:05 -07:00
|
|
|
method,
|
|
|
|
headers,
|
|
|
|
});
|
|
|
|
await checkResponseStatus(res);
|
|
|
|
|
|
|
|
return res;
|
|
|
|
}
|
|
|
|
|
|
|
|
async function fetchEndpointAsText(endpoint, options) {
|
|
|
|
const res = await fetchEndpoint(endpoint, options);
|
|
|
|
const data = await res.text();
|
|
|
|
return data;
|
|
|
|
}
|
|
|
|
|
|
|
|
async function fetchEndpointAsJson(endpoint, options) {
|
|
|
|
const opts = {
|
|
|
|
...options,
|
2022-02-10 00:42:02 -07:00
|
|
|
headers: {
|
|
|
|
'Content-Type': 'application/json',
|
2022-02-23 20:25:05 -07:00
|
|
|
...(options.headers || {}),
|
2022-02-10 00:42:02 -07:00
|
|
|
},
|
2022-02-23 20:25:05 -07:00
|
|
|
};
|
|
|
|
|
|
|
|
const res = await fetchEndpoint(endpoint, opts);
|
2022-02-10 00:42:02 -07:00
|
|
|
const data = await res.json();
|
|
|
|
return data;
|
|
|
|
}
|
|
|
|
|
2022-02-23 20:25:05 -07:00
|
|
|
module.exports = {
|
|
|
|
fetchEndpoint,
|
|
|
|
fetchEndpointAsText,
|
|
|
|
fetchEndpointAsJson,
|
|
|
|
};
|