Files
notesnook/packages/core/utils/http.js

118 lines
2.6 KiB
JavaScript
Raw Normal View History

2020-12-16 12:06:25 +05:00
function get(url, token) {
return request(url, token, "GET");
}
function deleteRequest(url, token) {
return request(url, token, "DELETE");
}
function patch(url, data, token) {
return bodyRequest(url, data, token, "PATCH");
2020-12-16 12:06:25 +05:00
}
patch.json = function (url, data, token) {
return bodyRequest(url, data, token, "PATCH", "application/json");
};
2020-12-16 12:06:25 +05:00
function post(url, data, token) {
return bodyRequest(url, data, token, "POST");
2020-12-16 12:06:25 +05:00
}
post.json = function (url, data, token) {
return bodyRequest(url, data, token, "POST", "application/json");
2020-12-16 12:06:25 +05:00
};
export default {
get,
post,
delete: deleteRequest,
patch,
};
function transformer(data, type) {
2020-12-23 11:28:38 +05:00
if (!data) return;
if (type === "application/json") return JSON.stringify(data);
2020-12-16 12:06:25 +05:00
else {
return Object.entries(data)
.map(
([key, value]) =>
`${encodeURIComponent(key)}=${encodeURIComponent(value)}`
)
.join("&");
}
}
async function handleResponse(response) {
const contentType = response.headers.get("content-type");
if (contentType && contentType.includes("application/json")) {
const json = await response.json();
if (response.ok) {
return json;
}
throw new Error(errorTransformer(json));
2020-12-16 12:06:25 +05:00
} else {
2021-01-03 12:33:40 +05:00
if (response.status === 429) throw new Error("You are being rate limited.");
2020-12-16 12:06:25 +05:00
if (response.ok) return await response.text();
else
throw new Error(
`Request failed with status code: ${response.status} ${response.statusText}.`
);
}
}
async function request(url, token, method) {
return handleResponse(
await fetch(url, {
method,
2020-12-16 13:23:14 +05:00
headers: getAuthorizationHeader(token),
2020-12-16 12:06:25 +05:00
})
);
}
async function bodyRequest(
url,
data,
token,
method,
contentType = "application/x-www-form-urlencoded"
) {
2020-12-16 12:06:25 +05:00
return handleResponse(
await fetch(url, {
method,
body: transformer(data, contentType),
2020-12-16 12:06:25 +05:00
headers: {
2020-12-16 13:23:14 +05:00
...getAuthorizationHeader(token),
"Content-Type": contentType,
2020-12-16 12:06:25 +05:00
},
})
);
}
2020-12-16 13:23:14 +05:00
function getAuthorizationHeader(token) {
return token ? { Authorization: "Bearer " + token } : {};
}
function errorTransformer(errorJson) {
if (!errorJson.error && !errorJson.errors && !errorJson.error_description)
return "Unknown error.";
const { error, error_description, errors } = errorJson;
if (errors) {
return errors.join("\n");
}
switch (error) {
case "invalid_grant": {
switch (error_description) {
case "invalid_username_or_password":
return "Username or password incorrect.";
default:
return error_description || error;
}
}
default:
return error_description || error;
}
}