mailbucket
Version:
An npm library that aggregates multiple APIs for creating and receiving temporary emails.
69 lines (68 loc) • 2.57 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.makeRequest = void 0;
async function makeRequest(url, options, expectedStatus = 200 | 201 | 204 | 205) {
try {
const fetchOptions = {
method: options.method,
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
...(options.headers || {}),
},
};
if (options.body) {
fetchOptions.body = typeof options.body === 'string' ? options.body : JSON.stringify(options.body);
}
else if (options.method === 'POST' || options.method === 'PUT' || options.method === 'PATCH') {
if (!fetchOptions.headers['Content-Type']) {
fetchOptions.headers['Content-Type'] = 'application/json';
}
}
let requestUrl = url;
if (options.params) {
const query = new URLSearchParams(options.params).toString();
if (query) {
requestUrl += `?${query}`;
}
}
const response = await fetch(requestUrl, fetchOptions);
let responseData;
const contentType = response.headers.get('content-type');
if (response.status === 204) {
responseData = null;
}
else if (contentType?.includes('application/json')) {
responseData = await response.json();
}
else {
responseData = await response.text();
}
if (!response.ok) {
const message = responseData?.message || responseData?.detail || responseData?.error || (typeof responseData === 'string' ? responseData : response.statusText);
return {
success: false,
status: response.status,
message: `API Error: ${message || 'Unknown error'}`,
error: responseData,
};
}
const expectedStatuses = Array.isArray(expectedStatus) ? expectedStatus : [expectedStatus];
if (!expectedStatuses.includes(response.status)) {
}
return {
success: true,
status: response.status,
data: responseData,
};
}
catch (error) {
console.error(`Request failed for ${options.method} ${url}:`, error);
return {
success: false,
message: `Network or client error: ${error.message || 'Unknown client error'}`,
error: error,
};
}
}
exports.makeRequest = makeRequest;