Skip to content

Instantly share code, notes, and snippets.

@ivankisyov
Created January 30, 2019 08:18
Show Gist options
  • Save ivankisyov/57e74c37b52d1555f37abf6bfa2994e9 to your computer and use it in GitHub Desktop.
Save ivankisyov/57e74c37b52d1555f37abf6bfa2994e9 to your computer and use it in GitHub Desktop.
Making multiple http requests and logging debugging info
const axios = require("axios");
const postTo = "https://jsonplaceholder.typicode.com/posts";
const patchTo = "https://jsonplaceholder.typicode.com/posts/2"; // todo: make the patch endpoint dynamic
const itemsToBePosted = [
{ title: "foo", body: "bar", userId: 1 },
{ title: "foo", body: "bar", userId: 2 },
{ title: "foo", body: "bar", userId: 3 },
{ title: "foo", body: "bar", userId: 4 }
];
function postMutlipleItems(itemsToBePosted) {
itemsToBePosted.forEach(itemToBePosted => {
// post items
axios
.post(postTo, itemToBePosted)
.then(postData => {
const { status, data } = postData;
successfullRequesLogger(status, data, itemToBePosted, "Post");
return patchItem(itemToBePosted, patchTo);
})
.then(patchData => {
const { status, data } = patchData;
successfullRequesLogger(status, data, itemToBePosted, "Patch");
})
.catch(err => {
console.log("Error message>>", err.message);
console.log("Error code>>", err.code);
});
});
}
function successfullRequesLogger(status, data, processedItem, httpOperation) {
console.log(
`status: ${status}, item with userId ${processedItem.userId} saved`
);
console.log(`${httpOperation} data: `, data);
}
function patchItem(itemToPatch, patchTo) {
return axios.patch(patchTo, {
title: `title for item with ${itemToPatch.userId} patched`
});
}
postMutlipleItems(itemsToBePosted);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment