Skip to content

Instantly share code, notes, and snippets.

@ryanjyost
Last active November 26, 2019 20:41
Show Gist options
  • Select an option

  • Save ryanjyost/2a2a95a0f5e39e74a96d5fb0f2c71a1c to your computer and use it in GitHub Desktop.

Select an option

Save ryanjyost/2a2a95a0f5e39e74a96d5fb0f2c71a1c to your computer and use it in GitHub Desktop.
await for axios and return a normalized object in async/await
const qs = require("qs");
module.exports = function(promise) {
const normalized = {
error: "Something went wrong",
data: null,
ok: false,
original: null,
status: null
};
return promise
.then(response => {
normalized.original = response;
normalized.data = normalizeDataToJson(
response.data,
response.headers["content-type"]
);
normalized.status = response.status;
const { status } = response;
if (isOk(status)) {
normalized.ok = true;
normalized.error = null;
return normalized;
}
normalized.error = normalizeDataToJson(
response.data,
response.headers["content-type"]
);
return normalized;
})
.catch(err => {
console.log("ERROR", err);
normalized.error = err;
normalized.data = normalizeDataToJson(
response.data,
response.headers["content-type"]
);
normalized.status = response.status;
return normalized;
});
};
function isOk(status) {
return status >= 200 && status < 300;
}
function normalizeDataToJson(data, contentType) {
if (contentType.includes("application/x-www-form-urlencoded")) {
return qs.parse(data);
}
return data;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment