Skip to content

Instantly share code, notes, and snippets.

@tracker1

tracker1/request.js

Created Apr 5, 2019
Embed
What would you like to do?
fetch api wrapper - request
import changeObjectCase from 'change-object-case';
import base from '../../base';
import HttpStatus from 'http-status-codes';
const serverCase = input =>
changeObjectCase.pascalKeys(input, { recursive: true, arrayRecursive: true });
export const headRequest = async route => {
const token = sessionStorage.getItem('token');
const headers = {
authorization: `Bearer ${token}`,
accept: 'application/json;q0.9,*/*;1=0.5',
};
const response = await fetch(`${base.api}${route}`, {
method: 'HEAD',
headers,
});
const status = response.status;
await response.text();
return { statusCode: status, message: HttpStatus.getStatusText(status) };
};
export const normalizeRequest = async (method, route, body) => {
let response;
let status;
let text;
let data;
let error;
try {
const token = sessionStorage.getItem('token');
const headers = {
authorization: `Bearer ${token}`,
accept: 'application/json;q0.9,*/*;1=0.5',
};
if (body) {
headers['Content-Type'] = 'application/json; charset=utf-8';
}
response = await fetch(`${base.api}${route}`, {
method: method.toUpperCase(),
headers,
body: body ? JSON.stringify(serverCase(body)) : undefined,
});
status = response.status;
if (response.status === 401 || response.status === 403) {
throw new Error('API Request Unauthorized');
}
text = await response.text();
if (!text && response.status >= 200 && response.status < 300) return null;
if (text) {
data = JSON.parse(text);
// simple scalar values
if (typeof data === 'string' || typeof data === 'number') {
return data;
}
data = Array.isArray(data)
? changeObjectCase.camelArray(data, { recursive: true, arrayRecursive: true })
: changeObjectCase.camelKeys(data, { recursive: true, arrayRecursive: true });
if (data && data.hasOwnProperty('value') && Object.keys(data).length === 1) {
if (!data.value) return data.value;
return data.value;
}
}
} catch (err) {
error = err;
}
if (!error && data?.error) {
// error property on data means error
error = data?.error;
}
if (!error && !data && +status >= 300) {
error = Object.assign(new Error(HttpStatus.getStatusText(status) || 'UnexpectedError'), {
statusCode: status,
});
}
if (error) {
if (typeof error === 'string') error = { message: error };
error.statusCode = +(error.statusCode || error.status) || +status || 999;
error.internal = { text, response };
}
if (error) throw error;
return data || { raw: text };
};
export default normalizeRequest;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment